Exchanger--线程执行过程中交换数据

 1 import java.util.concurrent.Exchanger;
 2 import java.util.concurrent.ExecutorService;
 3 import java.util.concurrent.Executors;
 4 
 5 /**
 6  * @author sulishi
 7  * @version 1.0
 8  * @date 2021/1/31
 9  */
10 public class ExchangerTest {
11     private static final Exchanger<String> exgr = new Exchanger<String>();
12     private static ExecutorService threadPool = Executors.newFixedThreadPool(2);
13 
14     public static void main(String[] args) {
15         threadPool.execute(new Runnable() {
16             @Override
17             public void run() {
18                 try {
19                     // 线程A执行结果
20                     String threadResultOfA = "111";
21                     exgr.exchange(threadResultOfA);
22                 }
23                 catch (InterruptedException e) {
24                 }
25             }
26         });
27         threadPool.execute(new Runnable() {
28             @Override
29             public void run() {
30                 try {
31                     // 线程B执行结果
32                     String threadResultOfB = "222";
33                     String a = exgr.exchange(threadResultOfB);
34                     System.out.println("数据是否一致:" + a.equals(threadResultOfB));
35                 }
36                 catch (InterruptedException e) {
37                 }
38             }
39         });
40         threadPool.shutdown();
41     }
42 }

结果: 数据不一致

如果两个线程有一个没有执行exchange()方法,则会一直等待,如果担心有特殊情况发生,避免一直等待,可以使用exchange(V x,longtimeout,TimeUnit unit)设置最大等待时长。

上一篇:TaskScheduler介绍【转】


下一篇:Spring Boot运用多线程实例