首页 > 代码库 > 并发包交换数据Exchanger

并发包交换数据Exchanger

/** *  * @描述: 用于实现两个人之间的数据交换,每个人完成一定的事务后想与对方交换数据,第一个先拿出数据的人一直等待 * 直到第二个人拿到数据 到来时,才能彼此交换数据. * @作者: Wnj . * @创建时间: 2017年5月16日 . * @版本: 1.0 . */public class ExchangerTest {        public static void main(String[] args) {        ExecutorService service = Executors.newCachedThreadPool();        final Exchanger exchanger = new Exchanger();        service.execute(new Runnable() {            public void run() {                try {                                        String data1 = "zxx";                    System.out.println("线程:" + Thread.currentThread().getName() + "正准备把数据" + data1 + "换过去");                    Thread.sleep((long)(Math.random() * 10000));                    String data2 = (String)exchanger.exchange(data1);                    System.out.println("线程:" + Thread.currentThread().getName() + "换回数据" + data2);                }                catch (Exception e) {                                    }            }        });        service.execute(new Runnable() {            public void run() {                try {                                        String data1 = "lhm";                    System.out.println("线程:" + Thread.currentThread().getName() + "正准备把数据" + data1 + "换过去");                    Thread.sleep((long)(Math.random() * 10000));                    String data2 = (String)exchanger.exchange(data1);                    System.out.println("线程:" + Thread.currentThread().getName() + "换回数据" + data2);                }                catch (Exception e) {                                    }            }        });    }}

 

并发包交换数据Exchanger