concurrent包下的Exchanger练习

Exchanger可以在两个线程之间交换数据,只能是2个线程,他不支持更多的线程之间互换数据。

当线程A调用Exchange对象的exchange()方法后,他会陷入阻塞状态,直到线程B也调用了exchange()方法,然后以线程安全的方式交换数据,之后线程A和B继续运行。

 1 package cn.sp.test4;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import java.util.concurrent.Exchanger;
 6 
 7 /**
 8  * Created by 2YSP on 2017/9/1.
 9  * 两个线程之间交换数据
10  */
11 public class ExchangerTest {
12 
13 
14     public static void main(String[] args) {
15         final Exchanger<List<Integer>> exchanger = new Exchanger<>();
16 
17         new Thread(() -> {
18             List<Integer> l = new ArrayList<Integer>(2);
19             l.add(1);
20             l.add(2);
21             try {
22                 l = exchanger.exchange(l);
23             } catch (InterruptedException e) {
24                 e.printStackTrace();
25             }
26             System.out.println("thread1: " + l);
27         }).start();
28 
29         new Thread(() -> {
30             List<Integer> l = new ArrayList<Integer>(2);
31             l.add(3);
32             l.add(4);
33             try {
34                 l = exchanger.exchange(l);
35             } catch (InterruptedException e) {
36                 e.printStackTrace();
37             }
38             System.out.println("thread2: " + l);
39         }).start();
40 
41     }
42 }

执行结果:

可以看到线程1和2已经交换了数据。

原文地址:https://www.cnblogs.com/2YSP/p/7483584.html