首页 > 其他 > 详细

Exchanger

时间:2019-11-18 00:14:49      阅读:104      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!