BlockingQueue 是线程安全的,并且在调用 put,take 方法时会阻塞线程。
基于以上特性,可以不加任何锁解决生产者消费者问题。
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> bq = new LinkedBlockingQueue<>(2);
CountDownLatch cdl = new CountDownLatch(2);
Thread t1 = new Thread(()->{ // 生产者线程
try {
for (int i = 0; i < 100; i++)
bq.put("z" + i);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
cdl.countDown();
}
});
Thread t2 = new Thread(()->{ // 消费者线程
try {
for (int i = 0; i < 100; i++)
System.out.println(bq.take());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
cdl.countDown();
}
});
t2.start();
t1.start();
cdl.await(); // 等待两个线程结束
System.out.println(bq.size());
}