Exchanger用于两个线程间交换数据。说起来这个和前面讲过的SynchronousQueue比较像。但是比
SynchronousQueue
功能更强大的是可以双向交换数据。
在发生数据交换的时候的行为也和SynchronousQueue
比较像:
- 如果线程1想要和线程2交换数据,此时线程2并未准备好,那么此时线程1就会进入block状态
- 线程2准备好,线程1解除block状态,发生数据交换
来个示例:
public void testExchange() {
Exchanger<String> stringExchanger = new Exchanger<>();
CallThread callThread = new CallThread(stringExchanger);
AnswerThread answerThread = new AnswerThread(stringExchanger);
callThread.start();
answerThread.start();
}
static class CallThread extends Thread {
Exchanger<String> stringExchanger;
public CallThread(Exchanger<String> stringExchanger) {
setName("CallThread");
this.stringExchanger = stringExchanger;
}
@Override
public void run() {
super.run();
try {
String call = stringExchanger.exchange("Call");
System.out.println(Thread.currentThread().getName() + " " + call);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class AnswerThread extends Thread {
Exchanger<String> stringExchanger;
public AnswerThread(Exchanger<String> stringExchanger) {
setName("AnswerThread");
this.stringExchanger = stringExchanger;
}
@Override
public void run() {
super.run();
try {
String answer = stringExchanger.exchange("Answer");
System.out.println(Thread.currentThread().getName() + " " + answer);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
看下输出:
image.png
可以看到两个线程的数据发生了交换。
网友评论