public class Test {
static final FiFoBlockingQueue<Message> queue = new FiFoBlockingQueue<>(10);
public static void main(String[] args) {
Producer producer = new Producer(queue);
Consumer c1 = new Consumer(queue);
Consumer c2 = new Consumer(queue);
producer.start();
c1.start();
c2.start();
}
}
直接上例子,我们用 ReentrantLock 实现一个简单的“FIFO 的阻塞队列”
FiFoBlockingQueue.java
Message.java
Producer.java
Consumer.java
Test.java
我们借助于 Condition 来判断队列是否为空、是否满,在为空的时候通知 Producer 生产,在满的时候通知 Consumer 消费。
关于 Condition 原理,参考: