乐趣区

java并发编程学习之Exchanger

作用

用来交换两个线程的数据。

示例

public class ExchangerDemo {static Exchanger<String> exchanger = new Exchanger<>();

    static class Thread1 extends Thread {
        @Override
        public void run() {
            try {sleep(3000);
                String str = exchanger.exchange("a");
                System.out.println(Thread.currentThread().getName() + "-" + str);
            } catch (InterruptedException e) {e.printStackTrace();
            }
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            try {String str = exchanger.exchange("b");
                System.out.println(Thread.currentThread().getName() + "-" + str);
            } catch (InterruptedException e) {e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread1.start();
        thread2.start();}
}

运行结果如下:

首先,会经过三秒后,才输出结果,说明两个线程没交换之前是阻塞的。输出结果可以看出,两个线程的字符串交换了。

退出移动版