标签:
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 }
标签:
原文地址:http://www.cnblogs.com/litaiqing/p/4651013.html