码迷,mamicode.com
首页 > 其他好文 > 详细

Exchanger

时间:2019-11-17 23:39:00      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:bsp   cep   The   received   数据   exchange   except   ace   dex   

exchanger用于两个线程交换数据

/**
 * 两个线程交换数据,A线程发送数据给B线程,B线程接受的数据和A发送的数据是同一个对象
 *  A  will send  the Object java.lang.Object@6e22e576
 *  B  will send  the Object java.lang.Object@248711b7
 *  B  received the Object java.lang.Object@6e22e576
 *  A  received the Object java.lang.Object@248711b7
 */
public class ExchangerTest {

    public static void main(String[] args) {
        final  Exchanger<Object> exchanger = new Exchanger<>();

        new Thread(() -> {
            Object obj = new Object();
            System.out.println( " A  will send  the Object " + obj);
            try {
                Object rObj = exchanger.exchange(obj);
                System.out.println( " A  received the Object " + rObj);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            Object obj = new Object();
            System.out.println( " B  will send  the Object " + obj);
            try {
                Object rObj = exchanger.exchange(obj);
                System.out.println( " B  received the Object " + rObj);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

 

Exchanger

标签:bsp   cep   The   received   数据   exchange   except   ace   dex   

原文地址:https://www.cnblogs.com/moris5013/p/11879211.html

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