java线程中Exchanger使用

jopen 10年前

有时我们需要对元素进行配对和交换线程的同步点,使用exchange方法 返回其伙伴的对象,这时我们就需要使用线程类中的Exchanger类了,

我通过一个实例 来简单说明一下他的使用方法及其作用:

    import java.util.concurrent.Exchanger;        import java.util.concurrent.ExecutorService;        import java.util.concurrent.Executors;                        public class TestExchanger {                    /**            * @param args            */            public static void main(String[] args) {                 ExecutorService executor = Executors.newCachedThreadPool();                 final Exchanger<String> exchanger = new Exchanger<String>();                 executor.execute(new Runnable() {                    String data1 = "abc";                    @Override                    public void run() {                        try {                            System.out.println(Thread.currentThread().getName() +"正在把数据 "+ data1+ " 交换出去" );                            Thread.sleep((long) (Math.random()*1000));                                                        String data2 = (String) exchanger.exchange(data1);                            System.out.println(Thread.currentThread().getName() + "交换数据 到  "+ data2);                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                });                                  executor.execute(new Runnable() {                     String data1 = "def";                    @Override                    public void run() {                        try {                            System.out.println(Thread.currentThread().getName() +"正在把数据 "+ data1+ " 交换出去" );                            Thread.sleep((long) (Math.random()*1000));                                                        String data2 = (String) exchanger.exchange(data1);                            System.out.println(Thread.currentThread().getName() + "交换数据 到  "+ data2);                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                });            }                }  

执行完毕之后;你会发现数据完成交换

pool-1-thread-1正在把数据 abc 交换出去
pool-1-thread-2正在把数据 def 交换出去
pool-1-thread-2交换数据 到  abc
pool-1-thread-1交换数据 到  def