01 Exchanger 作用
使两个线程之间进行数据传递。(对是两个之间而不是三个或者更多个线程之间)
02 常用方法
exchange()
阻塞当前线程并等待其他线程来取得数据,若没有其他线程来取数据则一直等待。
exchange()
传递数据
exchange(V v, long timeout, TimeUnit unit)
在指定的时间内没收到消息,则抛出超时的异常。
03 例子
package com.page.concurrent.exchanger;
import java.util.concurrent.Exchanger;
public class Worker extends Thread {
private final String name;
Exchanger<String> exchanger;
public Worker(String name, Exchanger<String> exchanger) {
this.name = name;
this.exchanger = exchanger;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " : " +
System.currentTimeMillis() +
" " + name +
" waiting message.");
try {
String exchange = exchanger.exchange("I'm " + name);
System.out.println(name + " get message : " + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.page.concurrent.exchanger;
import java.util.concurrent.Exchanger;
public class App {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
for (int i = 1; i <= 2; i++) {
new Worker("people-" + i, exchanger)
.start();
}
}
}