首页 > 代码库 > Java并发程序设计(21)并发锁之交换器Exchanger

Java并发程序设计(21)并发锁之交换器Exchanger

 

1.1. 交换器Exchanger

 

Exchanger用于在两个线程之间同步的同时交换数据,并且仅仅可以用于两个线程之间,不支持多个线程之间交换。

 

package com.test.concurrence;

 

import java.util.concurrent.Exchanger;

 

public class ExchangerTest {

 

public static void main(String[] args) {

//待交换数据的类型为字符串。

final Exchanger<String>  exchanger = new Exchanger<String>();

String[] tags = new String[]{"A","B"};

for(int j=0;j<2;j++){

final String tag = tags[j];

new Thread( new Runnable(){

@Override

public void run(){

for(int i=0;i<10;i++){

try {

String old = tag+i;

//执行效果:对方变成old,自己得到result。

Object result = exchanger.exchange(old);

System.out.println( old + " => " + result +" , " + Thread.currentThread().getName());

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}).start();

}

 

 

}

 

}

 

 

运行结果如下:

A0 => B0 , Thread-0

B0 => A0 , Thread-1

B1 => A1 , Thread-1

A1 => B1 , Thread-0

A2 => B2 , Thread-0

B2 => A2 , Thread-1

A3 => B3 , Thread-0

B3 => A3 , Thread-1

B4 => A4 , Thread-1

A4 => B4 , Thread-0

A5 => B5 , Thread-0

B5 => A5 , Thread-1

B6 => A6 , Thread-1

A6 => B6 , Thread-0

A7 => B7 , Thread-0

B7 => A7 , Thread-1

A8 => B8 , Thread-0

B8 => A8 , Thread-1

B9 => A9 , Thread-1

A9 => B9 , Thread-0

 

Java并发程序设计(21)并发锁之交换器Exchanger