通过SynchronousQueue方式实现线程间数据传递
线程 A 与线程 B 共同持有一个 SynchronousQueue 的引用,线程 B 调用 take 方法,阻塞以等待; 线程 A 运行
后计算出结果,将结果 put 到 queue 中。
package com.example.synchronousqueuedemo;
import java.util.concurrent.SynchronousQueue;
/**
* @author tom
*/
public class SynchronousQueueTest {
public static void main(String[] args) {
SynchronousQueue<Integer> queue = new SynchronousQueue<Integer>();
// 线程A putThread
Thread putThread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("put thread start");
try {
Thread.sleep(3000);
System.out.println("put thread put对象");
queue.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("put thread end");
}
});
//线程B takeThread
Thread takeThread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("take thread start");
try {
System.out.println("take thread 等待put对象");
System.out.println("take from putThread: " + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("take thread end");
}
});
putThread.start();
takeThread.start();
}
}
# 程序输出
take thread start
take thread 等待put对象
put thread start
put thread put对象
put thread end
take from putThread: 1
take thread end