话不多说,直接上代码:
/*
测试Exchange的功能,交换两个线程的数据
*/
public class Exc {
//这个是交换两个线程之间的字符串集合
public static Exchanger<Set<String>> exchanger = new Exchanger<Set<String>>();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
Set<String> setA = new HashSet<>();
setA.add("cheng");
setA.add("yi");
setA.add("ming");
System.out.println("原来的setA:"+setA);
try {
setA = exchanger.exchange(setA);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("后来的setA:"+setA);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Set<String> setB = new HashSet<>();
setB.add("liu");
setB.add("dun");
setB.add("sheng");
System.out.println("原来的setB:"+setB);
try {
setB = exchanger.exchange(setB);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("后来的setB:"+setB);
}
}).start();
}
}
结果:
原来的setA:[yi, ming, cheng]
原来的setB:[liu, dun, sheng]
后来的setB:[yi, ming, cheng]
后来的setA:[liu, dun, sheng]
网友评论