BlockingQueue est thread-safe, et le mettre d'appel, va bloquer les discussions méthode RECOIT.
Sur la base des caractéristiques ci-dessus, peuvent être résolus sans les producteurs et les consommateurs de verrouillage.
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());
}