生产者消费者队列,顾名思义,就是一个队列,不停地有生产者在里面生产对象并通知阻塞的消费者可以消费了,如果队列满了,生产者就阻塞不能再生产;消费者来消费(也就是读取并拿走队列里的对象)并通知阻塞的生产者,直到把队列消费空,就阻塞不能再消费。
2020.3.2更新:
原来的代码不是特别简练,修改了一下,参考的是youtube上一个博主的实现,实现的还是挺简练的。
BlockingQueue版本的实现
public class ProducerConsumerQueueBlockingQueue {
/** BlockingQueue实现的生产者消费者模式 **/
public static void main(String[] args) {
BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(10);
final Runnable producer = () -> {
while(true){
try {
//blockingQueue.put(ItemFactory.createItem());
blockingQueue.put(new Object());
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
for (int i=0; i<5; ++i)
new Thread(producer).start();
final Runnable consumer = () -> {
while(true){
try {
Object item = blockingQueue.take();
// process(item);
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
for (int i=0; i<5; ++i)
new Thread(consumer).start();
}
}
Condition的await/signal版本实现
public class ProducerConsumerQueue<E> {
private Queue<E> queue;
private int max = 16;
private Object notFull;
private Object notEmpty;
public ProducerConsumerQueue(int size){
queue = new LinkedList<>();
this.max = size;
notFull = new Object();
notEmpty = new Object();
}
public synchronized void put(E element){
while(queue.size() == max){
try {
notFull.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
queue.add(element);
notEmpty.notifyAll();
}
public synchronized E take(){
while(queue.size()==0){
try {
notEmpty.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
E element = queue.remove();
notFull.notifyAll();
return element;
}
public static void main(String[] args) {
ProducerConsumerQueue<Object> pc = new ProducerConsumerQueue(10);
final Runnable producer = ()->{
while(true)
pc.put(new Object());
};
final Runnable consumer = ()->{
while(true){
Object obj = pc.take