Exchanger

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();
    }
}

 

posted @ 2019-11-17 23:17  踏月而来  阅读(226)  评论(0编辑  收藏  举报