一,以下是使用exchange实现线程1和线程2的数据交换,执行后控制台将输出 线程2拿到的数据这是我线程1的数据,11111111
线程1拿到的数据这是我线程2的数据,2222222
public class ExchangeTest {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
ExecutorService service = Executors.newCachedThreadPool();
//线程1获得线程2数据
service.execute(new Runnable() {
@Override
public void run() {
try {
String content = exchanger.exchange("这是我线程1的数据,11111111");
System.out.println("线程1拿到的数据"+content);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//线程2获取线程1数据
service.execute(new Runnable() {
@Override
public void run() {
try {
String content = exchanger.exchange("这是我线程2的数据,2222222");
System.out.println("线程2拿到的数据"+content);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
service.shutdown();
}
}
|
|