阻塞队列BlockingQueue一 SynchronousQueue

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();

    }

}

 

posted @ 2019-05-13 01:20  fuguang  阅读(192)  评论(0编辑  收藏  举报