方法为exchange.exchange(要替换的值):(注:只能两个线程替换)
/**
*类说明:Exchange的使用,两个线程之间的数据交换(注:只能两个线程,所以很局限)
*/
public class UseExchange {
private static final Exchanger<Set<String>> exchange
= new Exchanger<>();
public static class Test implements Runnable{
@Override
public void run() {
Set<String> setA = new HashSet<>();//存放数据的容器
try {
setA.add("one");
for(String value:setA){
System.out.println("Thread_"+Thread.currentThread().getId()+"交换前值为"+value);
}
setA = exchange.exchange(setA);//交换set
/*处理交换后的数据*/
for(String value:setA){
System.out.println("Thread_"+Thread.currentThread().getId()+"交换后值为"+value);
}
} catch (InterruptedException e) {
}
}
}
public static void main(String[] args) {
final Thread one =new Thread(new Test());
//第一个线程
one.start();
//第二个线程
new Thread(new Runnable() {
@Override
public void run() {
Set<String> setB = new HashSet<>();//存放数据的容器
try {
setB.add("two");
for(String value:setB){
System.out.println("Thread_"+Thread.currentThread().getId()+"交换前值为"+value+"\n---------------");
}
setB = exchange.exchange(setB);//交换set
/*处理交换后的数据*/
one.join();
for(String value:setB){
System.out.println("Thread_"+Thread.currentThread().getId()+"交换后值为"+value);
}
} catch (InterruptedException e) {
}
}
}).start();
}
}