线程:Exchanger同步工具

可以在对中对元素进行配对和交换的线程的同步点,类似于交易,A拿着钱到达指定地点,B拿着物品到达指定地点,相互交换,然后各自忙各自的事去了。

 1 package ch03;

 2 

 3 import java.util.concurrent.Exchanger;

 4 

 5 public class ExchangerTest {

 6 

 7     public static void main(String[] args) {

 8         final Exchanger<String> changer = new Exchanger<>();

 9         new Thread(new Runnable() {

10             

11             @Override

12             public void run() {

13                 try{

14                     String data1 = "xyy";

15                     System.out.println("交换前,"+Thread.currentThread().getName()+"的数据是:"+data1);

16                     //等待交易

17                     String afterChange = changer.exchange(data1);

18                     System.out.println("交换后,"+Thread.currentThread().getName()+"的数据是:"+afterChange);

19                 }catch (Exception e) {

20                 }

21             }

22         }).start();

23         

24         new Thread(new Runnable() {

25             

26             @Override

27             public void run() {

28                 try{

29                     String data1 = "zy";

30                     System.out.println("交换前,"+Thread.currentThread().getName()+"的数据是:"+data1);

31                     //等待交易

32                     String afterChange = changer.exchange(data1);

33                     System.out.println("交换后,"+Thread.currentThread().getName()+"的数据是:"+afterChange);

34                 }catch (Exception e) {

35                 }

36             }

37         }).start();

38     }

39 

40 }

 

你可能感兴趣的:(Exchanger)