SynchronousQueue:不存储元素的阻塞队列,也即单个元素的队列
是阻塞队列的一个实现类,没有容量,与其他的BlockQueue不同,SynchronousQueue是一个不存储元素的BlockQueue,每一个put操作必须等待一个take消费,否则不能消费,也就是说,生产一个消费一个
public class HelloGC {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> blockingQueue = new SynchronousQueue<>();
new Thread(() -> {
try
{
System.out.println(Thread.currentThread().getName()+"\t put 1");
blockingQueue.put("1");
System.out.println(Thread.currentThread().getName()+"\t put 2");
blockingQueue.put("2");
System.out.println(Thread.currentThread().getName()+"\t put 3");
blockingQueue.put("3");
}catch (InterruptedException e){
e.printStackTrace();
}
},"AAA").start();
new Thread(() -> {
try{
TimeUnit.SECONDS.sleep(5);
System.out.println(blockingQueue.take());
TimeUnit.SECONDS.sleep(5);
System.out.println(blockingQueue.take());
TimeUnit.SECONDS.sleep(5);
System.out.println(blockingQueue.take());
}catch (InterruptedException e){
e.printStackTrace();
}
},"BBB").start();
}
}
结果: