SynchronousQueue是一个不存储元素的阻塞队列。当队列有1个元素时,必须被消费才可以再存入
*测试代码中可看到 put一个元素立马能take一个元素
public class BlockingQueueDemo2 { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> demo = new SynchronousQueue<>(); new Thread(() -> { try { System.out.println(Thread.currentThread().getName()+":put元素1"); demo.put("a"); System.out.println(Thread.currentThread().getName()+":put元素2"); demo.put("b"); System.out.println(Thread.currentThread().getName()+":put元素3"); demo.put("c"); } catch (Exception e) { e.printStackTrace(); } }, "A线程").start(); new Thread(()->{ try { TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+":"+demo.take()); TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+":"+demo.take()); TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+":"+demo.take()); } catch (Exception e) { e.printStackTrace(); } },"B线程").start(); } }
原文地址:https://www.cnblogs.com/fuguang/p/10854525.html
时间: 2024-10-05 12:05:34