用于实现两个线程间的数据交换,每个线程在完成一定的任务后想与对方交换数据,第一个先拿出数据的线程将一直等待第二个线程拿着数据到来时,才能彼些交换数据.
public class ExchangerTest {
public static void main(String[] args) {
final Exchanger<String> exchanger = new Exchanger<String>();
ExecutorService service = Executors.newCachedThreadPool();
service.execute(new Runnable() {
public void run() {
try {
String data1 = "人民币";
System.out.println("线程" + Thread.currentThread().getName()
+ "正在把数据" + data1 + "换出去");
Thread.sleep((long) (Math.random() * 10000));
String data2 = exchanger.exchange(data1);
System.out.println("线程" + Thread.currentThread().getName()
+ "换回的数据为" + data2);
} catch (Exception e) {
e.printStackTrace();
}
}
});
service.execute(new Runnable() {
public void run() {
try {
String data1 = "白粉";
System.out.println("线程" + Thread.currentThread().getName()
+ "正在把数据" + data1 + "换出去");
Thread.sleep((long) (Math.random() * 10000));
String data2 = exchanger.exchange(data1);
System.out.println("线程" + Thread.currentThread().getName()
+ "换回的数据为" + data2);
} catch (Exception e) {
e.printStackTrace();
}
}
});
service.shutdown();
}
}