Java并发编程:核心方法与框架
上QQ阅读APP看书,第一时间看更新

1.2.3 方法exchange(V x, long timeout, TimeUnit unit)与超时

当调用exchange(V x, long timeout, TimeUnit unit)方法后在指定的时间内没有其他线程获取数据,则出现超时异常。

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


        package extthread;
        import java.util.concurrent.Exchanger;
        import java.util.concurrent.TimeUnit;
        import java.util.concurrent.TimeoutException;
        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", 5, TimeUnit.SECONDS));
                    System.out.println("A end! ");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    //TODO Auto-generated catch block
                    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-31所示。

图1-31 出现超时异常