JAVA多线程-Exchanger

JAVA.util.concurrent.Exchanger类代表了两个线程在一个集合点可以交互数据 。下面描述了一下机制:
 

JAVA多线程-Exchanger

文章插图
两个线程通过Exchanger 正在交换对象数据
交换对象数据是通过 exchange()方法,下面是例子:
Exchanger exchanger = new Exchanger();ExchangerRunnable exchangerRunnable1 =  new ExchangerRunnable(exchanger, "A"); ExchangerRunnable exchangerRunnable2 =        new ExchangerRunnable(exchanger, "B"); new Thread(exchangerRunnable1).start();new Thread(exchangerRunnable2).start();【JAVA多线程-Exchanger】 
ExchangerRunnable代码:
public class ExchangerRunnable implements Runnable{   Exchanger exchanger = null;   Object    object    = null;    public ExchangerRunnable(Exchanger exchanger, Object object) {       this.exchanger = exchanger;       this.object = object;   }    public void run() {       try {           Object previous = this.object;            this.object = this.exchanger.exchange(this.object);            System.out.println(Thread.currentThread().getName() +    " exchanged " + previous + " for " + this.object   );      } catch (InterruptedException e) {           e.printStackTrace();       }   }} 
执行结果:
Thread-0 exchanged A for BThread-1 exchanged B for A 
参考翻译:http://tutorials.jenkov.com/java-util-concurrent/exchanger.html




    推荐阅读