BlockingQueue is thread-safe, and the call put, will block threads take method.
Based on the above characteristics, can be solved without any lock producers and consumers.
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());
}