Exchanger

作者: From64KB | 来源:发表于2020-11-18 10:16 被阅读0次

    Exchanger用于两个线程间交换数据。说起来这个和前面讲过的SynchronousQueue比较像。但是比
    SynchronousQueue功能更强大的是可以双向交换数据。

    image.png

    在发生数据交换的时候的行为也和SynchronousQueue比较像:

    1. 如果线程1想要和线程2交换数据,此时线程2并未准备好,那么此时线程1就会进入block状态
    2. 线程2准备好,线程1解除block状态,发生数据交换

    来个示例:

        public void testExchange() {
            Exchanger<String> stringExchanger = new Exchanger<>();
    
            CallThread callThread = new CallThread(stringExchanger);
            AnswerThread answerThread = new AnswerThread(stringExchanger);
    
            callThread.start();
            answerThread.start();
        }
    
        static class CallThread extends Thread {
            Exchanger<String> stringExchanger;
    
            public CallThread(Exchanger<String> stringExchanger) {
                setName("CallThread");
                this.stringExchanger = stringExchanger;
            }
    
            @Override
            public void run() {
                super.run();
                try {
                    String call = stringExchanger.exchange("Call");
                    System.out.println(Thread.currentThread().getName() + " " + call);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        static class AnswerThread extends Thread {
            Exchanger<String> stringExchanger;
    
            public AnswerThread(Exchanger<String> stringExchanger) {
                setName("AnswerThread");
                this.stringExchanger = stringExchanger;
            }
    
            @Override
            public void run() {
                super.run();
                try {
                    String answer = stringExchanger.exchange("Answer");
                    System.out.println(Thread.currentThread().getName() + " " + answer);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    

    看下输出:


    image.png

    可以看到两个线程的数据发生了交换。

    相关文章

      网友评论

          本文标题:Exchanger

          本文链接:https://www.haomeiwen.com/subject/alxfiktx.html