java.util.concurrent.Exchanger 是用來支持兩個線程之間交換數(shù)據(jù)绣檬,不支持更多線程摔吏。class represents a kind of rendezvous point where two threads can exchange objects. Here is an illustration of this mechanism:
當線程A調(diào)用exchange()方法時嵌屎,將會阻塞新蟆,直到另一個線程也調(diào)用此方法砚哗。以一個線程安全的方式交換數(shù)據(jù)。
例子如下
Exchanger exchanger = new Exchanger();
ExchangerRunnable exchangerRunnable1 =
new ExchangerRunnable(exchanger, "A");
ExchangerRunnable exchangerRunnable2 =
new ExchangerRunnable(exchanger, "B");
new Thread(exchangerRunnable1).start();
new Thread(exchangerRunnable2).start();
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();
}
}
}