1.2.2 方法exchange()传递数据

创建测试用的项目Exchanger_2,创建ThreadA.java类代码如下:


     package extthread;
     import java.util.concurrent.Exchanger;
     public class ThreadA extends Thread {
        private Exchanger<String> exchanger;
        public ThreadA(Exchanger<String> exchanger) {
            super();
            this.exchanger = exchanger;
        }
        @Override
        public void run() {
            try {
                System.out.println("在线程A中得到线程B的值=" + exchanger.exchange("中国人A"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

创建ThreadB.java类代码如下:


    package extthread;
    import java.util.concurrent.Exchanger;
    public class ThreadB extends Thread {
        private Exchanger<String> exchanger;
        public ThreadB(Exchanger<String> exchanger) {
            super();
            this.exchanger = exchanger;
        }
        @Override
        public void run() {
            try {
                System.out.println("在线程B中得到线程A的值=" + exchanger.exchange("中国人B"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

运行类Run.java代码如下:


    package test.run;
    import java.util.concurrent.Exchanger;
    import extthread.ThreadA;
    import extthread.ThreadB;
    public class Run {
        public static void main(String[] args) {
                  Exchanger<String> exchanger = new Exchanger<String>();
                  ThreadA a = new ThreadA(exchanger);
                  ThreadB b = new ThreadB(exchanger);
                  a.start();
                  b.start();
              }
          }

程序运行后的效果如图1-30所示。

图1-30 成功交换数据