线程辅助类(一)--Exchanger

线程辅助类Exchanger通常用于在两个线程间,在某一同步点,进行数据交换。

一、关键点如下:

1、泛型定义数据交换的类型,如Exchanger exchanger = new Exchanger<>();

2、 exchanger.exchange(data),进行数据交换,参数是用去交换的数据,返回值是交换回来的结果;

二、实例如下:

public class ExchangerMain {

    public static void main(String[] args) {

        ExecutorService es = Executors.newFixedThreadPool(2);
        Exchanger exchanger = new Exchanger<>();
        es.submit(new ThreadOne(exchanger));
        es.submit(new ThreadTwo(exchanger));
        es.shutdown();
    }


    static class ThreadOne implements Callable{

        private Exchanger exchanger;

        public ThreadOne(Exchanger exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public String call() throws Exception {
            String data = "one";
            System.out.println(Thread.currentThread().getName() + " wait change data : "+data);
            String newData = exchanger.exchange(data);
            System.out.println(Thread.currentThread().getName()+ " change data success ,newData : "+ newData);
            return null;
        }
    }

    static class ThreadTwo implements Callable{

        private Exchanger exchanger;

        public ThreadTwo(Exchanger exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public String call() throws Exception {
            String data = "two";
            System.out.println(Thread.currentThread().getName() + " wait change data : "+data);
            String newData = exchanger.exchange(data);
            System.out.println(Thread.currentThread().getName()+ " change data success ,newData : "+ newData);
            return null;
        }
    }

}

运行结果:

pool-1-thread-1 wait change data : one
pool-1-thread-2 wait change data : two
pool-1-thread-2 change data success ,newData : one
pool-1-thread-1 change data success ,newData : two





你可能感兴趣的:(java多线程)