可以在對中對元素進行配對和交換的線程的同步點。每個線程將條目上的某個方法呈現給exchange方法,與伙伴線程進行匹配,並且在返回時接收其伙伴的對象。Exchanger 可能被視為SynchronousQueue的雙向形式。Exchanger 可能在應用程序(比如遺傳算法和管道設計)中很有用。
Exchanger提供的是一個交換服務,允許原子性的交換兩個(多個)對象,但同時只有一對才會成功。
現在啟動兩個線程,分別發送一個信息,然後通過exchanger交換信息。
代碼:
1 public class ExchangerTest {
2 public static void main(String[] args) {
3 ExecutorService threadPool = Executors.newCachedThreadPool();
4 final Exchanger exchanger = new Exchanger();
5
6 threadPool.execute(new Runnable() {
7
8 @Override
9 public void run() {
10 String date1 = "love";
11 System.out.println("Thread "+Thread.currentThread().getName()+"正在把數據"+date1+"放入!");
12 try {
13 Thread.sleep(new Random().nextInt(1000));
14 } catch (InterruptedException e) {
15 // TODO Auto-generated catch block
16 e.printStackTrace();
17 }
18 String date2 = null;
19 try {
20 date2 = (String) exchanger.exchange(date1);
21 } catch (InterruptedException e) {
22 // TODO Auto-generated catch block
23 e.printStackTrace();
24 }
25 System.out.println("Thread "+Thread.currentThread().getName()+"得到數據"+date2);
26 }
27 });
28 threadPool.execute(new Runnable() {
29
30 @Override
31 public void run() {
32 String date1 = "hate";
33 System.out.println("Thread "+Thread.currentThread().getName()+"正在把數據"+date1+"放入!");
34 try {
35 Thread.sleep(new Random().nextInt(1000));
36 } catch (InterruptedException e) {
37 // TODO Auto-generated catch block
38 e.printStackTrace();
39 }
40 String date2 = null;
41 try {
42 date2 = (String) exchanger.exchange(date1);
43 } catch (InterruptedException e) {
44 // TODO Auto-generated catch block
45 e.printStackTrace();
46 }
47 System.out.println("Thread "+Thread.currentThread().getName()+"得到數據"+date2);
48 }
49 });
50
51 threadPool.shutdown();
52 }
53 }
Exchanger實現的是一種數據分片的思想,這在大數據情況下將數據分成一定的片段並且多線程執行的情況下有一定的使用價值。