2019-06-13 16:29:00
浏览数 (1)
- Exchanger用于进行线程间的数据交换。
- 提供一个同步点,在这个同步点,两个线程可以交换彼此的数据。
- 第一个线程执行exchange方法,阻塞等待第二个线程也执行exchange方法,都到达同步点时,线程就可以交换数据
- exchange(V x, long timeout, TimeUnit unit)方法可以超时等待
代码语言:javascript
复制import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author pengjunzhe
*/
public class ExchangerTest {
private static Exchanger<String> exchanger = new Exchanger<>();
private static ExecutorService threadpool = Executors.newFixedThreadPool(2);
public static void main(String[] args) {
threadpool.execute(() -> {
String A = "银行流水A";
try {
String C = exchanger.exchange(A);
System.out.println("A收到的是:" C);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadpool.execute(() -> {
try {
String B = "银行流水B";
String A= exchanger.exchange("B");
System.out.println("A和B数据是否一致:" A.equals(B) ", A录入的是:" A ",B录入的是:" B);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadpool.shutdown();
}
}