Exchanger(交换器)

Exchanger用于两个线程之间的数据交换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class ExchangerDemo {
static Exchanger<String> exchanger = new Exchanger<>();

public static void main(String[] args) {
new Thread(()->{
String s = "T1";
try {
s = exchanger.exchange(s);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + s);

}, "t1").start();


new Thread(()->{
String s = "T2";
try {
s = exchanger.exchange(s);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + s);

}, "t2").start();
}
}

注意,如果一个线程调用了exchange,另一个线程没有调用或者怎么,会导致第一个线程一直被阻塞,永久等待,直到有可以进行配对的线程;

而且这仅限于两个线程,当出现第三个线程的时候就会随机交换,因为不确定是哪个跟 哪个的交换