JUC同步队列SynchronousQueue

同步队列SynchronousQueue:没有容量,进去一个元素,必须等待取出来之后,才能再往里面放一个元素!
具体方法:put,take
api中的描述:在这里插入图片描述
代码实现:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class SynchronousQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> queue=new SynchronousQueue<>();
        new Thread(()->{
            try {

                System.out.println(Thread.currentThread().getName()+"放入了"+"a");
                queue.put("a");

                System.out.println(Thread.currentThread().getName()+"放入了"+"b");
                queue.put("b");

                System.out.println(Thread.currentThread().getName()+"放入了"+"c");
                queue.put("c");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(5);
                System.out.println(Thread.currentThread().getName()+"取到了"+queue.take());
                TimeUnit.SECONDS.sleep(5);
                System.out.println(Thread.currentThread().getName()+"取到了"+queue.take());
                TimeUnit.SECONDS.sleep(5);
                System.out.println(Thread.currentThread().getName()+"取到了"+queue.take());

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();




    }
}

具体效果:

Thread-0放入了a
Thread-1取到了a
Thread-0放入了b
Thread-1取到了b
Thread-0放入了c
Thread-1取到了c

Process finished with exit code 0

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页