Exchanger用法详解
Exchanger适用场景
Exchanger用于线程之间交换数据,其使用代码很简单,主要是使用是一个exchange()方法。
一个简单的例子如下
Exchanger<String> exchanger = new Exchanger<>();
new Thread(()->{
System.out.println(" thread 1 ");
try {
String exchange = exchanger.exchange(" thread 1 send data ");
System.out.println(" thread 1 revicer data : " + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
System.out.println(" thread 2 ");
try {
String exchange = exchanger.exchange(" thread 2 send data ");
System.out.println(" thread 2 revicer data : " + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
2个线程之间彼此交换数据
如果我们一个线程执行超时,另一个线程是否会等待?
Exchanger<String> exchanger = new Exchanger<>();
new Thread(()->{
System.out.println(" thread 1 ");
try {
String exchange = exchanger.exchange(" thread 1 send data ",2, TimeUnit.SECONDS);
System.out.println(" thread 1 revicer data : " + exchange);
} catch (InterruptedException | TimeoutException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
System.out.println(" thread 2 ");
try {
TimeUnit.SECONDS.sleep(5);
String exchange = exchanger.exchange(" thread 2 send data ");
System.out.println(" thread 2 revicer data : " + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
我们可以看到是等待的,会一直阻塞在哪儿。
使用时尽量使用超时时间的那个先换方法 public V exchange(V x, long timeout, TimeUnit unit)
那如果我们选择交换一个对象呢?该对象是否是安全的?
Object object = new Object();
Exchanger<Object> exchanger = new Exchanger<>();
new Thread(()->{
System.out.println(" thread 1 ");
try {
Object exchange = exchanger.exchange(object);
System.out.println(" thread 1 revicer data : " + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
System.out.println(" thread 2 ");
try {
Object exchange = exchanger.exchange(object);
System.out.println(" thread 2 revicer data : " + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
可以看到对象是一样的,交换对象时候需要注意对象的安全。多个线程下需要注意线程同步问题。