同步队列(SynchronizedQueue)

同步队列(SynchronizedQueue)存一个值必须先取出存入的值,才能继续存值,可以理解为容量为0的BlockingQueue。如果想存两个值,那就会一直等待阻塞。注意需要在线程中使用,普通方法使用时会发生阻塞

package com.luoKing.BlockingQueue;

import java.util.concurrent.SynchronousQueue;

public class sychronizedQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        SynchronousQueue<String> queue = new SynchronousQueue<>();
        new Thread(
                () -> {
                    try {
                        System.out.println(Thread.currentThread().getName()+" put a ");
                        queue.put("a");
                        System.out.println(Thread.currentThread().getName()+" put b ");
                        queue.put("b");
                        System.out.println(Thread.currentThread().getName()+" put c ");
                        queue.put("c");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        ,"put").start();

        new Thread(()->{
            try {
                System.out.println(queue.take());
                System.out.println(queue.take());
                System.out.println(queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();


    }
}
//运行结果

put put a 
a
put put b 
b
put put c 
c


posted @ 2022-05-06 23:18  小罗要有出息  阅读(940)  评论(0编辑  收藏  举报