Java并发-28.并发工具类-Exchanger
作者:
悠扬前奏 | 来源:发表于
2019-06-06 22:38 被阅读0次
- Exchanger用于进行线程间的数据交换。
- 提供一个同步点,在这个同步点,两个线程可以交换彼此的数据。
- 第一个线程执行exchange方法,阻塞等待第二个线程也执行exchange方法,都到达同步点时,线程就可以交换数据
- exchange(V x, long timeout, TimeUnit unit)方法可以超时等待
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();
}
}
本文标题:Java并发-28.并发工具类-Exchanger
本文链接:https://www.haomeiwen.com/subject/eozvzqtx.html
网友评论