1、Exchanger 入门
Exchanger
:交换器。用于在线程之间交换数据,但是比较受限,因为只能两个线程之间交换数据
public class Test {
public static void main(String[] args) throws InterruptedException {
Exchanger<Set<String>> exchanger = new Exchanger<>();
Runnable taskA = () -> {
Set<String> aSet = new HashSet<>();
aSet.add("A");
aSet.add("B");
aSet.add("C");
try {
Set<String> exchange = exchanger.exchange(aSet);
System.out.println(Thread.currentThread().getName() + " " + exchange);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
Runnable taskB = () -> {
Set<String> bSet = new HashSet<>();
bSet.add("a");
bSet.add("b");
bSet.add("c");
try {
Set<String> exchange = exchanger.exchange(bSet);
System.out.println(Thread.currentThread().getName() + " " + exchange);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
new Thread(taskA, "threadA").start();
new Thread(taskB, "threadB").start();
}
}
运行结果:
threadB [A, B, C]
threadA [a, b, c]
2、Exchanger 源码解析
略