同步佇列(SynchronizedQueue)
阿新 • • 發佈:2022-05-07
同步佇列(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