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

17.Java5的Exchanger同步工具

时间:2015-07-16 16:12:46      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

 1 import java.util.concurrent.Exchanger;
 2 import java.util.concurrent.ExecutorService;
 3 import java.util.concurrent.Executors;
 4 
 5 /**
 6  * Java5的Exchanger同步工具
 7  * 用于实现两个人之间的数据交换,每个人在完成一定的事务后想与对方交换数据,
 8  * 第一个先拿出数据的人将一直等待第二个人那这数据到来时,才能彼此交换数据
 9  * @author LiTaiQing
10  *
11  */
12 public class ExchangerTest {
13     public static void main(String[] args) {
14         ExecutorService service = Executors.newCachedThreadPool();
15         final Exchanger<String> exchanger = new Exchanger<String>();
16         service.execute(new Runnable() {
17             public void run() {
18                 try {
19 
20                     String data1 = "zxx";
21                     System.out.println("线程" + Thread.currentThread().getName()
22                             + "正在把数据" + data1 + "换出去");
23                     Thread.sleep((long) (Math.random() * 10000));
24                     String data2 = (String) exchanger.exchange(data1);
25                     System.out.println("线程" + Thread.currentThread().getName()
26                             + "换回的数据为" + data2);
27                 } catch (Exception e) {
28 
29                 }
30             }
31         });
32         service.execute(new Runnable() {
33             public void run() {
34                 try {
35 
36                     String data1 = "lhm";
37                     System.out.println("线程" + Thread.currentThread().getName()
38                             + "正在把数据" + data1 + "换出去");
39                     Thread.sleep((long) (Math.random() * 10000));
40                     String data2 = (String) exchanger.exchange(data1);
41                     System.out.println("线程" + Thread.currentThread().getName()
42                             + "换回的数据为" + data2);
43                 } catch (Exception e) {
44 
45                 }
46             }
47         });
48     }
49 }

 

17.Java5的Exchanger同步工具

标签:

原文地址:http://www.cnblogs.com/litaiqing/p/4651013.html

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