码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-12-25 16:02:22      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:i++   and   inf   star   syn   --   for   vat   生产者   

技术图片

 

参考代码:

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();
}
}

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

标签:i++   and   inf   star   syn   --   for   vat   生产者   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!