主要并发工具类-Exchanger的使用
2020-02-10 本文已影响0人
飞奔吧牛牛
Exchanger 从字面来看是一个交换器,它用来在线程间交换数据。
到exchange方法处时会阻塞,传递给对方数据,并等待对方数据的到来。
Exchanger<String> exchanger = new Exchanger<>();
new Thread(() -> {
System.out.println("Thread A do something...");
try {
String result = exchanger.exchange("string from A");
System.out.println("Thread A get " + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
System.out.println("Thread B do something...");
try {
String result = exchanger.exchange("string from B");
System.out.println("Thread B get " + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
结果:
Thread A do something...
Thread B do something...
Thread A get string from B
Thread B get string from A