生产者与消费者模式,是一道非常经典的设计模式,所涉及到的是多线程协调工作的问题。在Java中,一般是通过wait()和notify()方法进行解决。
下面附上关于这种设计模式的源码:
//仓库类
public class Store {
private final int MAX_SIZE;//仓库的最大容量
private int count;//当前的货物数量
public Store(int n){//初始化最大容量的构造方法
MAX_SIZE = n;
count = 0;
}
//往仓库加货物的方法
public synchronized void add(){
while(count >= MAX_SIZE){//每次执行都判断仓库是否已满
System.out.println("已经满了");
try {
this.wait();//如果满了,就进入等待池
} catch (Exception e) {
e.printStackTrace();
}
}
count++;//数量加1
//打印当前仓库的货物数量
System.out.println(Thread.currentThread().toString()+"put"+count);
//仓库中已经有东西可以取了,则通知所有的消费者线程来拿
this.notifyAll();
}
//从仓库拿走货物的方法
public synchronized void remove(){
while(count<=0){
System.out.println("空了");//每次执行都判断仓库是否为空
try {
this.wait();//如果为空,就进入等待池
} catch (Exception e) {
e.printStackTrace();
}
}
//打印当前仓库的货物数量
System.out.println(Thread.currentThread(