快速理解:一个线程在执行exchange(set)之后,会等待另一个线程执行exchange(set),然后两个线程继续往下执行
图解
示例代码:交换数据
public class UseExchange {
private static final Exchanger<Set<String>> exchange = new Exchanger<Set<String>>();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
Set<String> setA = new HashSet<String>();//存放数据的容器
try {
Thread.currentThread().setName("setA:");
System.out.println("setA原来是:a,b,c,d");
//添加数据
setA.add("a");
setA.add("b");
setA.add("c");
setA.add("d");
Thread.sleep(1000);
setA = exchange.exchange(setA);//交换set
System.out.println("交换之后" + Thread.currentThread().getName() + setA.toString());
/*处理交换后的数据*/
} catch (InterruptedException e) {
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Set<String> setB = new HashSet<String>();//存放数据的容器
Thread.currentThread().setName("setB:");
System.out.println("setB原来是:1,2,3,4");
try {
//添加数据
setB.add("1");
setB.add("2");
setB.add("3");
setB.add("4");
setB = exchange.exchange(setB);//交换set
System.out.println("交换之后" + Thread.currentThread().getName() + setB.toString());
/*处理交换后的数据*/
} catch (InterruptedException e) {
}
}
}).start();
}
}
执行结果:
setA原来是:a,b,c,d
setB原来是:1,2,3,4
交换之后setA:[1, 2, 3, 4]
交换之后setB:[a, b, c, d]