Java Exchanger类用于两个线程之间互相交换数据。当两方执行不对称的操作使,例如当一个线程向缓冲区写入数据,另一个线程从缓冲区中读取数据。这些线程可以使用Exchanger来汇合,并将满的缓冲区与空的缓冲区交换。当两个线程通过Exchanger交换对象时,这种交换就把这两个对象安全的发布给另一方。(Java并发编程实战)
为了方便理解,提供一个最简单的例子来展示他的基本用法。
static class Exchange implements Runnable {
Exchanger<Integer> exchanger;
int data;
public Exchange(Exchanger exchanger, int data){
this.exchanger = exchanger;
this.data = data;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+":before exchange data="+data);
int exchangedData = exchanger.exchange(data);
System.out.println(Thread.currentThread().getName()+":after exchange data="+exchangedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
Exchanger<Integer> exchanger = new Exchanger<>();
new Thread(new Exchange(exchanger, 0)).start();
new Thread(new Exchange(exchanger, 1)).start();
}