1 Exchanger使用案例
public class ExchangerDemo {
public static void main(String[] args) {
Exchanger<Object> exchanger = new Exchanger<>();
new Thread(() -> {
Object object = new Object();
System.out.println(Thread.currentThread().getName() + "創(chuàng)建的對(duì)象是" + object);
try {
object = exchanger.exchange(object);
System.out.println(Thread.currentThread().getName() + "交換后得到的對(duì)象是" + object);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "線程1").start();
new Thread(() -> {
Object object = new Object();
System.out.println(Thread.currentThread().getName() + "創(chuàng)建的對(duì)象是" + object);
try {
TimeUnit.SECONDS.sleep(2);
object = exchanger.exchange(object);
System.out.println(Thread.currentThread().getName() + "交換后得到的對(duì)象是" + object);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "線程2").start();
}
}
結(jié)果
線程1創(chuàng)建的對(duì)象是java.lang.Object@2f992f4f
線程2創(chuàng)建的對(duì)象是java.lang.Object@42c40a13
線程2交換后得到的對(duì)象是java.lang.Object@2f992f4f
線程1交換后得到的對(duì)象是java.lang.Object@42c40a13