package demo;
import java.util.Random;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 这个类用来模拟吃饭和打饭时候交换 "碗"的过程
*
* @author king_wang
*
*/
public class ExchangerDemo {
public static void main(String[] args){
ExecutorService exePool=Executors.newFixedThreadPool(2);
//创建一个Exchange类型的对象用来进行两个线程之间的数据的转换
final Exchanger changer=new Exchanger();
//吃饭的线程;
Runnable eat = new Runnable(){
@Override
public void run() {
String cup="空的碗";
try {
System.out.println("正在吃饭。。。");
Thread.sleep(5000);
System.out.println("线程"+Thread.currentThread().getName()
+"正在把 " + cup + " 交换");
String cups=(String)changer.exchange(cup);
System.out.println("线程 " + Thread.currentThread().getName()
+ "换回的数据为 " + cups);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
//打饭的线程;
Runnable add = new Runnable(){
@Override
public void run() {
String cups="满的碗";
try {
System.out.println("正在打饭。。。");
Thread.sleep(8000);
System.out.println("线程"+Thread.currentThread().getName()
+"正在把 "+ cups + " 交换");
String cup=(String)changer.exchange(cups);
System.out.println("线程 " + Thread.currentThread().getName()
+ "换回的数据为 " + cup);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
exePool.execute(eat);
exePool.execute(add);
exePool.shutdown();
}
}
运行结果;
正在吃饭。。。
正在打饭。。。
线程pool-1-thread-1正在把 空的碗 交换
线程pool-1-thread-2正在把 满的碗 交换
线程 pool-1-thread-2换回的数据为 空的碗
线程 pool-1-thread-1换回的数据为 满的碗