码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-03-31 20:51:40      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:strong   字符   span   程序设计   err   catch   get   logs   java并发   

 

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

标签:strong   字符   span   程序设计   err   catch   get   logs   java并发   

原文地址:http://www.cnblogs.com/coe2coe/p/6653348.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!