线程通信原创
# Exchanger 进行线程通信
通过exchanger.exchange进行线程通信,双方线程必须都执行此方法,否则会阻塞等待
public class Test1 {
private static Exchanger exchanger = new Exchanger();
public static void main(String[] args) {
new Thread(() -> {
try {
Object exchange = exchanger.exchange("我是" + Thread.currentThread().getName() );
System.out.println(Thread.currentThread().getName() +"获取到了->" +exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
Object exchange = exchanger.exchange("我是" + Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() +"获取到了->" +exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
编辑 (opens new window)
上次更新: 2022/03/13, 21:24:24