比如生活中两个人,一个人有零食,另一个人有钱,他们两个想等价交换,对好口号在某个地方相见,一个人先到了之后,必须等另一个人带着需要的东西来了之后,才能开始hi交换。
代码:
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExchangeTest {
public static void main(String[] args) {
ExecutorService service =Executors.newCachedThreadPool();
final Exchanger exchanger = new Exchanger();
service.execute(new Runnable() {
@Override
public void run() {
try{
String data1 = "零食";
System.out.println("线程"+Thread.currentThread().getName()+
"正在把数据 "+data1+" 换出去");
Thread.sleep((long)Math.random()*10000);
String data2 = (String)exchanger.exchange(data1);
System.out.println("线程 "+Thread.currentThread().getName()+
"换回的数据为 "+data2);
}catch(Exception e){
e.printStackTrace();
}
}
});
service.execute(new Runnable() {
@Override
public void run() {
try{
String data1 = "钱";
System.out.println("线程"+Thread.currentThread().getName()+
"正在把数据 "+data1+" 交换出去");
Thread.sleep((long)(Math.random()*10000));
String data2 =(String)exchanger.exchange(data1);
System.out.println("线程 "+Thread.currentThread().getName()+
"交换回来的数据是: "+data2);
}catch(Exception e){
e.printStackTrace();
}
}
});
}
}
控制台输出:
线程pool-1-thread-1正在把数据 零食 换出去
线程pool-1-thread-2正在把数据 钱 交换出去
线程 pool-1-thread-1换回的数据为 钱
线程 pool-1-thread-2交换回来的数据是: 零食