同步队列SynchronizedQueue
没有容量,不存储元素,进去一个元素必须等待取出来之后才能再往里面放一个元素
put/take
public class SynchronizedQueue {
public static void main(String[] args) {
BlockingQueue<String> synchronizedQueue = new SynchronizedQueue<>();
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+"PUT 1");
synchronizedQueue.put("1");
System.out.println(Thread.currentThread().getName()+"PUT 2");
synchronizedQueue.put("2");
System.out.println(Thread.currentThread().getName()+"PUT 3");
synchronizedQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t1").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"GET 1"+synchronizedQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"GET 2"+synchronizedQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"GET 3"+synchronizedQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t2").start();
}
}