1、
》》 代码案例:
package multiThread.art;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 如果两个线程有一个没有执行 exchange() 方法 , 则会一直等待, 如果担心有特殊情况发生,
* 避免一直等待,可以使用 " public V exchange(V x, long timeout, TimeUnit unit) " 设置
* 最大等待时间
*/
public class ExchangerTest {
private static final Exchanger<String> exgr = new Exchanger<String>();
private static ExecutorService threadPool = Executors.newFixedThreadPool(2);
public static void main(String[] args) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
/**
* A 录入银行流水数据
*/
String A = "银行流水A";
exgr.exchange(A);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadPool.execute(new Runnable() {
@Override
public void run() {
/**
* B 录入银行流水数据
*/
try {
String B = "银行流水B";
String A = exgr.exchange(B);
System.out.println("A和B的数据是否一致"+ A.equals(B)+
",A 录入的是:" + A + ",B 录入的是:"+ B);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadPool.shutdown();
}
}