JAVA.util.concurrent.Exchanger類代表了兩個線程在一個集合點可以交互數(shù)據(jù)。下面描述了一下機(jī)制:
兩個線程通過Exchanger 正在交換對象數(shù)據(jù)
交換對象數(shù)據(jù)是通過 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();
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();
}
}
}
執(zhí)行結(jié)果:
Thread-0 exchanged A for BThread-1 exchanged B for A
參考翻譯:http://tutorials.jenkov.com/java-util-concurrent/exchanger.html