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

Posted lujunlong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生产者消费者模式&线程间通信的方法相关的知识,希望对你有一定的参考价值。

技术图片

 

参考代码:

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

以上是关于生产者消费者模式&线程间通信的方法的主要内容,如果未能解决你的问题,请参考以下文章

线程间的通信 与 线程池

线程间的通信同步方式与进程间通信方式

Java线程间通信之wait/notify

Java多线程的生产者与消费者模型,线程间的通信

java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)

线程间通信