可以在对中对元素进行配对和交换的线程的同步点,类似于交易,A拿着钱到达指定地点,B拿着物品到达指定地点,相互交换,然后各自忙各自的事去了。
package ch03; import java.util.concurrent.Exchanger; public class ExchangerTest { public static void main(String[] args) {
final Exchanger<String> changer = new Exchanger<>();
new Thread(new Runnable() { @Override
public void run() {
try{
String data1 = "xyy";
System.out.println("交换前,"+Thread.currentThread().getName()+"的数据是:"+data1);
//等待交易
String afterChange = changer.exchange(data1);
System.out.println("交换后,"+Thread.currentThread().getName()+"的数据是:"+afterChange);
}catch (Exception e) {
}
}
}).start(); new Thread(new Runnable() { @Override
public void run() {
try{
String data1 = "zy";
System.out.println("交换前,"+Thread.currentThread().getName()+"的数据是:"+data1);
//等待交易
String afterChange = changer.exchange(data1);
System.out.println("交换后,"+Thread.currentThread().getName()+"的数据是:"+afterChange);
}catch (Exception e) {
}
}
}).start();
} }