生产者消费者模式: 生产者消费者模式就是通过一个容器来解决生产者和消费者的强耦合问题。
具体工作方式: 生产者和消费者不会直接接触,而是通过一个阻塞队列来进行相互作用,生产者负责往里面放东西,而消费者负责取东西。当阻塞队列为空且消费者恰好要取的时候,此时消费者会调用wait方法阻塞,并通知生产者该往里面放东西了。反过来,生产者者发现队列已经满了的时候,会通知消费者。
代码示例:
public class 阻塞队列 {
private static final int CAPCITY = 5;
int[] arr = new int[CAPCITY];
int firstNum = 0;
int lastNum = 0;
int size = 0;
public synchronized void put(int element) throws InterruptedException{
if(size != arr.length){
wait();
}
arr[lastNum] = element;
lastNum += 1;
if(lastNum == arr.length){
lastNum = 0;
}
size++;
notifyAll();
}
public synchronized int take() throws InterruptedException{
int element;
if(size == 0){
wait();
}
element = arr[firstNum];
firstNum += 1;
if(firstNum == arr.length){
firstNum = 0;
}
size--;
notifyAll();
return element;
}
}