Exchanger是自jdk1.5起开始提供的工具套件,一般用于两个工作线程之间交换数据。在本文中我将采取由浅入深的方式来介绍分析这个工具类。
首先我们来看看官方的api文档中的叙述:
A synchronization point at which threads can pair and swap elements within pairs. Each thread presents some object on entry to the exchange method, matches with a partner thread, and receives its partner’s object on return. An Exchanger may be viewed as a bidirectional form of a SynchronousQueue. Exchangers may be useful in applications such as genetic algorithms and pipeline designs.
在以上的描述中,有几个要点:
- 此类提供对外的操作是同步的;
- 用于成对出现的线程之间交换数据;
- 可以视作双向的同步队列;
- 可应用于基因算法、流水线设计等场景。
构造方法:
public Exchanger()
public V exchange(V x) throws InterruptedException
public V exchange(V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException
从官方的javadoc可以知道
,如果它的伙伴线程此前已经调用了此方法,那么它的伙伴会被调度唤醒并与之进行对象交换,然后各自返回。如果它的伙伴还没到达交换点,那么当前线程将会被挂起,直至伙伴线程到达——完成交换正常返回;或者当前线程被中断——抛出中断异常;又或者是等候超时——抛出超时异常。
使用例子
下面创建两个生产者线程生产一些序列,然后通过Exchanger进行交换:
package concurrent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Exchanger;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ExchangerTest {
public static void main(String[] args) {
Exchanger<List<Integer>> exchanger = new Exchanger<>();
ThreadPoolExecutor executor=(ThreadPoolExecutor) Executors.newCachedThreadPool();
executor.execute(new Producer(exchanger));
executor.execute(new Producer(exchanger));
}
}
class Producer extends Thread {
List<Integer> list = new ArrayList<>();
Exchanger<List<Integer>> exchanger = null;
public Producer(Exchanger<List<Integer>> exchanger) {
super();
this.exchanger = exchanger;
}
@Override
public void run() {
Random rand = new Random();
int num;
num=rand.nextInt(10000);
list.add(num);
num=rand.nextInt(10000);
list.add(num);
num=rand.nextInt(10000);
list.add(num);
num=rand.nextInt(10000);
list.add(num);
num=rand.nextInt(10000);
list.add(num);
try {
System.out.println(Thread.currentThread().getName()+":交换前:");
print();
list = exchanger.exchange(list);
System.out.println(Thread.currentThread().getName()+":交换后:");
print();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void print(){
for(Integer i:list){
System.out.println(i);
}
}
}
}
执行结果:
pool-1-thread-1:交换前:
185
3669
9943
4364
7101
pool-1-thread-2:交换前:
1091
1364
7341
3755
4966
pool-1-thread-2:交换后:
185
3669
9943
4364
7101
pool-1-thread-1:交换后:
1091
1364
7341
3755
4966
其他同步辅助类:
Java并发编程-同步辅助类之Phaser
Java并发编程-同步辅助类之CyclicBarrier
Java并发编程-同步辅助类之CountDownLatch
Java并发编程-同步辅助类之Semaphore