SynchronousQueue阻塞的地方是在put进去一个元素即阻塞,没办法继续执行,除非其他线程take该队列的元素。
而ArrayBlockingQueue设置容量为1阻塞的地方是在下一次put,也就是说,put一个元素之后还能继续往下执行代码。
public class Queue {
public static void main(String[] args) throws InterruptedException {
testSynchronousQueue();
TimeUnit.SECONDS.sleep(10);
System.out.println("=================");
testBlockingQueue();
}
private static void testSynchronousQueue(){
BlockingQueue<String> blockingDeque = new SynchronousQueue<>();
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName() + "put 1");
blockingDeque.put("1");
System.out.println(Thread.currentThread().getName() + "put 2");
blockingDeque.put("2");
System.out.println(Thread.currentThread().getName() + "put 3");
blockingDeque.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take 1");
blockingDeque.take();
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take 2");
blockingDeque.take();
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take 3");
blockingDeque.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
private static void testBlockingQueue(){
BlockingQueue<String> blockingDeque = new ArrayBlockingQueue<>(1);
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName() + "put 1");
blockingDeque.put("1");
System.out.println(Thread.currentThread().getName() + "put 2");
blockingDeque.put("2");
System.out.println(Thread.currentThread().getName() + "put 3");
blockingDeque.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take 1");
blockingDeque.take();
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take 2");
blockingDeque.take();
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take 3");
blockingDeque.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}