一、Exchanger应用场景
二、一个Demo学明白Exchanger
public class MyExchanger {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
new Thread(()->{
String s = "Thread-1";
try {
s = exchanger.exchange(s);
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+":"+s);
} catch (InterruptedException e) {
e.printStackTrace();
}
},"Thread-1").start();
new Thread(()->{
String s = "Thread-2";
try {
s = exchanger.exchange(s);
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+":"+s);
} catch (InterruptedException e) {
e.printStackTrace();
}
},"Thread-2").start();
}
}