Exchange

97 阅读1分钟

主要用于两个线程数据交换,如果一个线程执行 exchange 方法,那么会一直等着第二个线程执行 exchange 方法,进行数据交换

    public static void main(String[] args)  {
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(new Runnable() {
            String thread1 = "thread1";
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "   " + thread1);
                try {
                    // 获取到交换后的数据
                    thread1 = exchanger.exchange(thread1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()  + "   " +  thread1);
            }
        }, "Thread1").start();

        new Thread(new Runnable() {
            String thread2 = "thread2";
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()  + "   " +  thread2);
                try {
                    thread2 = exchanger.exchange(thread2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()  + "   " +  thread2);
            }
        }, "Thread2").start();
    }


Thread1   thread1
Thread2   thread2
Thread2   thread1
Thread1   thread2