1.2.1 方法exchange()阻塞的特性

类Exchanger中的exchange()方法具有阻塞的特色,也就是此方法被调用后等待其他线程来取得数据,如果没有其他线程取得数据,则一直阻塞等待。

创建测试用的项目Exchanger_1,创建类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"));
                    System.out.println("A end! ");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

运行类Run.java代码如下:


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

程序运行效果如图1-29所示。

图1-29 出现阻塞效果