常用的并发工具类( 四 )

Exchanger这个类用于交换数据,只能用于两个线程 。当一个线程运行到 exchange() 方法时会阻塞,另一个线程运行到 exchange() 时,两者交换数据,然后执行后面的程序 。
package test;import java.util.concurrent.Exchanger;public class Test3 {    static class Producer extends Thread{   // 生产者线程        private Exchanger<Integer> exchanger;     // 交换标志        private static int data = 0;        Producer(String name, Exchanger<Integer> exchanger){            super("Producer-" + name);            this.exchanger = exchanger;        }        @Override        public void run(){            for (int i = 1; i < 5; i++) {                try {                    Thread.sleep(1000);                    data = i;                    System.out.println(getName() + "交换前:" + data);                    data = exchanger.exchange(data);        // 将此 data 与 消费者的 data 进行交换                    System.out.println(getName() + "交换后:" + data);                }catch (InterruptedException e){                    e.printStackTrace();                }            }        }    }    static class Consumer extends Thread{   // 消费者线程        private Exchanger<Integer> exchanger;   // 交换标志        private static int data = 0;        Consumer(String name, Exchanger<Integer> exchanger){            super("Consumer-" + name);            this.exchanger = exchanger;        }        @Override        public void run(){            while(true){                data = 0;                System.out.println(getName() + "交换前:" + data);                try{                    data = exchanger.exchange(data);   // 将此 data 与生产者的 data 进行交换,因为先执行到这,会阻塞知道生产者执行到交换                }catch (InterruptedException e){                    e.printStackTrace();                }                System.out.println(getName() + "交换后:" + data);            }        }    }    public static void main(String[] args) throws InterruptedException {        Exchanger<Integer> exchanger = new Exchanger<>();        new Producer("", exchanger).start();        new Consumer("", exchanger).start();        Thread.sleep(7000);    }}


推荐阅读