Java实现生产者消费者模式的三种方法
-
前言
生产者消费者模式是程序设计中非常常见的一种设计模式,被广泛运用在解耦、消息队列等场景。在现实世界中,我们把生产商品的一方称为生产者,把消费商品的一方称为消费者,有时生产者的生产速度特别快,但消费者的消费速度跟不上,俗称“产能过剩”,又或是多个生产者对应多个消费者时,大家可能会手忙脚乱。如何才能让大家更好地配合呢?这时在生产者和消费者之间就需要一个中介来进行调度,于是便诞生了生产者消费者模式。 -
BlockingQueue 实现生产者消费者模式
public static void main(String[] args) { BlockingQueue<Object> queue = new ArrayBlockingQueue<>(10); Runnable producer = () -> { while (true) { queue.put(new Object()); } }; new Thread(producer).start(); new Thread(producer).start(); Runnable consumer = () -> { while (true) { queue.take(); } }; new Thread(consumer).start(); new Thread(consumer).start(); }
-
Condition 实现生产者消费者模式
public class MyBlockingQueueForCondition { private Queue queue; private int max = 16; private ReentrantLock lock = new ReentrantLock(); private Condition notEmpty = lock.newCondition(); private Condition notFull = lock.newCondition(); public MyBlockingQueueForCondition(int size) { this.max = size; queue = new LinkedList(); } public void put(Object o) throws InterruptedException { lock.lock(); try { while (queue.size() == max) { notFull.await(); } queue.add(o); notEmpty.signalAll(); } finally { lock.unlock(); } } public Object take() throws InterruptedException { lock.lock(); try { while (queue.size() == 0) { notEmpty.await(); } Object item = queue.remove(); notFull.signalAll(); return item; } finally { lock.unlock(); } } }
-
wait/notify 实现生产者消费者模式
class MyBlockingQueue { private int maxSize; private LinkedList<Object> storage; public MyBlockingQueue(int size) { this.maxSize = size; storage = new LinkedList<>(); } public synchronized void put() throws InterruptedException { while (storage.size() == maxSize) { wait(); } storage.add(new Object()); notifyAll(); } public synchronized void take() throws InterruptedException { while (storage.size() == 0) { wait(); } System.out.println(storage.remove()); notifyAll(); } }