调用exchange方法,第一个调用的线程会进入bloking状态,等到下一个线程调用 会完成交换
abcde 如果5个线程都调用了exchange方法 最终是 ab交换 cd交换 e线程一直阻塞等待中。。。
还有一个重载的方法 V exchange(V v, long timeout, TimeUnit unit) 见名知意~
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
/**
* @author: zhouwei
* @version: v1.0
* @description: com.service.callgraphy.thread_learn
* @date:2021-01-25
*/
public class ExchangerL {
static Exchanger exchanger= new Exchanger();
public static void main(String[] args) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"start 100");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
int a =(int) exchanger.exchange(100);
System.out.println(Thread.currentThread().getName()+"交换拿到的值"+a);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"start 100000");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
int a =(int) exchanger.exchange(100000);
System.out.println(Thread.currentThread().getName()+"交换拿到的值"+a);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
打印结果:
Thread-0start 100
Thread-1start 100000
Thread-1交换拿到的值100
Thread-0交换拿到的值100000