java.util.concurrent.Exchanger 是用来支持两个线程之间交换数据,不支持更多线程。class represents a kind of rendezvous point where two threads can exchange objects. Here is an illustration of this mechanism:
Two threads exchanging objects via an Exchanger.当线程A调用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();
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();
}
}
}
网友评论