-
SynchronousQueue同步队列是没有容量的说法的。put一个值后,必须task后才能继续put值。
public class SynchronousQueueTest { public static void main(String[] args) { //SynchronousQueue没有容量 //put一个值后,必须task后才能继续put SynchronousQueue<String> synchronousQueue = new SynchronousQueue<>(); //写入线程 new Thread(()->{ try { System.out.println(Thread.currentThread().getName()+" put 1"); synchronousQueue.put("1"); System.out.println(Thread.currentThread().getName()+" put 2"); synchronousQueue.put("2"); System.out.println(Thread.currentThread().getName()+" put 3"); synchronousQueue.put("3"); } catch (InterruptedException e) { e.printStackTrace(); } },"T1").start(); //取出线程 //task获取值 如果没有就阻塞 new Thread(()->{ try { TimeUnit.SECONDS.sleep(3); String ss = synchronousQueue.take(); System.out.println(Thread.currentThread().getName()+" task " + ss); TimeUnit.SECONDS.sleep(3); ss = synchronousQueue.take(); System.out.println(Thread.currentThread().getName()+" task " + ss); TimeUnit.SECONDS.sleep(3); ss = synchronousQueue.take(); System.out.println(Thread.currentThread().getName()+" task " + ss); } catch (InterruptedException e) { e.printStackTrace(); } },"T2").start(); } }
执行结果
一定是先put,再task