同步队列
package Juc;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
/**
* 同步队列SynchronousQueue一次只允许一个元素,消费后才插入下个元素进入队列
*
*/
public class SynchronousQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> bq = new SynchronousQueue<>();
new Thread(() ->
{
try {
System.out.println(Thread.currentThread().getName()+"\t put 1");
bq.put("1");
System.out.println(Thread.currentThread().getName()+"\t put 2");
bq.put("2");
System.out.println(Thread.currentThread().getName()+"\t put 3");
bq.put("3");
} catch (Exception e) {
e.printStackTrace();
}
},"aa").start();
new Thread(() ->
{
try {
try{TimeUnit.SECONDS.sleep(5);}catch (Exception e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"\t "+bq.take());
try{TimeUnit.SECONDS.sleep(5);}catch (Exception e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"\t "+bq.take());
try{TimeUnit.SECONDS.sleep(5);}catch (Exception e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"\t "+bq.take());
} catch (Exception e) {
e.printStackTrace();
}
},"bb").start();
}
}