概述
SynchronousQueue实现了BlockingQueue接口,但与众不同的是,SynchronousQueue的容量恒为零,也就是说 put 操作无法直接返回,需要等待一个 take 操作才能返回,反之也成立
示例代码
public class TestSynchronousQueue {
public static void main(String[] args) {
BlockingQueue<String> synchronousQueue = new SynchronousQueue<>();
new Thread(()->{
try {
synchronousQueue.put(String.valueOf(1));
System.out.println("put " + 1);
TimeUnit.SECONDS.sleep(1);
synchronousQueue.put(String.valueOf(2));
System.out.println("put " + 2);
TimeUnit.SECONDS.sleep(1);
synchronousQueue.put(String.valueOf(3));
System.out.println("put " + 3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
for (int i = 0; i < 3; i++) {
new Thread(()->{
try {
System.out.println("take " + synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
}
运行效果
可以看出,即使多个 take 线程早早地开启了,但却需要等待 put 线程开启才能返回