同步队列

同步队列没有容量,也可以视为容量为 1 的队列;

同步队列进去一个元素之后,就必须等待取出该元素之后,才能往里继续添加下一个元素;(put了一个元素,就必须从里面先take出来,否则不能再put进去值!)

通过put 方法和 take 方法进行同步队列的存取操作;

SynchronousQueue 和 其他的BlockingQueue 不一样它不用于存储元素;

并且SynchronousQueue 的take是使用了lock锁保证线程安全的。

示例

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

public class SynchronousQueueExample {
    public static void main(String[] args) {
        SynchronousQueue<String> synchronousQueue = new java.util.concurrent.SynchronousQueue<>();

        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+" put 01");
                synchronousQueue.put("1");
                System.out.println(Thread.currentThread().getName()+" put 02");
                synchronousQueue.put("2");
                System.out.println(Thread.currentThread().getName()+" put 03");
                synchronousQueue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A线程").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);//睡眠2秒
                System.out.println(Thread.currentThread().getName()+" take 0"+synchronousQueue.take());
                System.out.println(Thread.currentThread().getName()+" take 0"+synchronousQueue.take());
                System.out.println(Thread.currentThread().getName()+" take 0"+synchronousQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B线程").start();
    }
}
A线程 put 01
B线程 take 01
A线程 put 02
B线程 take 02
A线程 put 03
B线程 take 03

参考教程:https://www.kuangstudy.com/

posted @ 2021-04-26 10:48  懒鑫人  阅读(224)  评论(0编辑  收藏  举报