java多线程 SynchronousQueue同步队列
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> sq = new SynchronousQueue<String>();
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + " -> " + "put 1");
sq.put("1");
System.out.println(Thread.currentThread().getName() + " -> " + "put 2");
sq.put("2");
System.out.println(Thread.currentThread().getName() + " -> " + "put 3");
sq.put("3");
} catch (Exception e) {
e.printStackTrace();
}
}, "T1").start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + " " + sq.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + " " + sq.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + " " + sq.take());
} catch (Exception e2) {
e2.printStackTrace();
}
}, "T2").start();
}
}
运行结果
T1 -> put 1
T2 1
T1 -> put 2
T2 2
T1 -> put 3
T2 3
特别鸣谢:狂神说Java老师的无私奉献
.
.
.
上一篇 java多线程(五)ArrayBlockingQueue阻塞队列
下一篇 java多线程(七) 线程池ThreadPoolExecutor