欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JUC-队列Queue-同步队列入门

程序员文章站 2022-03-25 13:03:04
/**@Author: CYW@Date: 2020/11/19 22:41SynchronousQueue:同步队列 继承于BlockingQueue,和其他的队列不同,它不存储元素,put进一个值就必须取出来才能再次put*/public class SynchronousQueueTest {public static void main(String[] args) {BlockingQueue blockingQueue = new SynchronousQueue<...

/**

  • @Author: CYW
  • @Date: 2020/11/19 22:41
  • SynchronousQueue:同步队列
  •  继承于BlockingQueue,和其他的队列不同,它不存储元素,put进一个值就必须取出来才能再次put
    

*/
public class SynchronousQueueTest {
public static void main(String[] args) {
BlockingQueue blockingQueue = new SynchronousQueue<>();

    new Thread(()->{
        try {
            System.out.println(Thread.currentThread().getName()+"put 1");
            blockingQueue.put("1");
            System.out.println(Thread.currentThread().getName()+"put 2");
            blockingQueue.put("2");
            System.out.println(Thread.currentThread().getName()+"put 3");
            blockingQueue.put("3");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    },"线程(put存)").start();
    new Thread(()->{
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+blockingQueue.take());
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+blockingQueue.take());
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+blockingQueue.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    },"线程(take取)").start();

}

}

本文地址:https://blog.csdn.net/weixin_44219219/article/details/109829643

相关标签: java queue