forked from janzolau1987/study-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExchangerTest.java
More file actions
55 lines (46 loc) · 1.43 KB
/
ExchangerTest.java
File metadata and controls
55 lines (46 loc) · 1.43 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.yaoyaohao.study.thread;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Exchanger示例
* 用于进行线程间的数据交换。它提供一个同步点,在这个同步点,两个线程可以交换彼此的数据。
*
* 应用场景:
* 》可以用于遗传算法:
* 》可以用于校对工作:
*
* @author liujianzhu
* @date 2016年8月3日 下午3:50:47
*/
public class ExchangerTest {
private static final Exchanger<String> exchanger = new Exchanger<>();
private static ExecutorService threadPool = Executors.newFixedThreadPool(2);
public static void main(String[] args) {
threadPool.execute(new Runnable() {
@Override
public void run() {
String A = "银行流水A";
try {
String x = exchanger.exchange(A);
System.out.println("A线程得到的交换数据 : " + x);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadPool.execute(new Runnable() {
@Override
public void run() {
String B = "银行流水B";
try {
String A = exchanger.exchange(B);
System.out.println("A和B数据是否一致 : " + A.equals(B) + " , A录入的是 : " + A + " , B录入的是 : " + B);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadPool.shutdown();
}
}