import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Exchanger;
public class UseExchanger {
//两个线程间的数据交换
private static Exchanger<HashMap<String,Long>> exchanger = new Exchanger<>();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
HashMap<String,Long> mapA = new HashMap<>();
mapA.put(Thread.currentThread().getName(),Thread.currentThread().getId());
try {
mapA = exchanger.exchange(mapA);
for (Map.Entry<String,Long> result : mapA.entrySet()){
System.out.println("Thread : "+Thread.currentThread().getName()+"map :"+result.getKey());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
HashMap<String,Long> mapB = new HashMap<>();
mapB.put(Thread.currentThread().getName(),Thread.currentThread().getId());
try {
mapB = exchanger.exchange(mapB);
for (Map.Entry<String,Long> result : mapB.entrySet()){
System.out.println("Thread : "+Thread.currentThread().getName()+"map :"+result.getKey());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}