首页 > 编程语言 > 详细

生产者、消费者模式&线程间通信的方法

时间:2019-12-25 15:41:37      阅读:86      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

参考代码:

package aaa;


public class Goods {
private String name;
private String brand;
boolean isFlag;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Goods(String name, String brand) {
super();
this.name = name;
this.brand = brand;
}
public Goods() {
super();
}


public synchronized void set(String name,String brand) {

if (isFlag) {
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

this.setName(name);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.setBrand(brand);
System.out.println("生产者线程生产了"+this.getBrand()+"-----"+this.getName());
super.notify();
isFlag=true;

}

public synchronized void get() {

if (!isFlag) {
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

System.out.println("消费者线程取走了---"+getBrand()+"---"+getName());
super.notify();
isFlag=false;

}

}

 

 

 

package aaa;

public class Product implements Runnable{

public Product(Goods goods) {
super();
this.goods = goods;
}

public Goods getGoods() {
return goods;
}

public void setGoods(Goods goods) {
this.goods = goods;
}

private Goods goods;

public void run() {
for (int i = 0; i < 20; i++) {
if (i%2!=0) {
goods.set("旺仔", "小馒头");
}else {
goods.set("哇哈哈", "矿泉水");
}



}
}
}

 

 

 

package aaa;

public class Custmer implements Runnable{
private Goods goods;

public Custmer() {
super();
}

public Custmer(Goods goods) {
super();
this.goods = goods;
}

public Goods getGoods() {
return goods;
}

public void setGoods(Goods goods) {
this.goods = goods;
}

public void run() {
for (int i = 0; i < 20; i++) {
goods.get();
}
}
}

 

 

 

package aaa;

public class Test {
public static void main(String[] args) {
Goods goods = new Goods();
Product product = new Product(goods);
Custmer custmer = new Custmer(goods);

Thread t1 = new Thread(product);
Thread t2 = new Thread(custmer);
t1.start();
t2.start();
}
}

生产者、消费者模式&线程间通信的方法

原文:https://www.cnblogs.com/LuJunlong/p/12096939.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!