11.5.4线程 同步装置之Exchanger

本文通过模拟服务生为顾客提供饮料的服务过程,详细阐述了如何利用Exchanger类实现线程间的信息高效交换。具体包括初始化Exchanger对象,指定交换信息类型,以及服务生和顾客线程如何通过调用exchange方法完成杯子的交换,从而实现连续的服务流程。

/**

*Exchanger让两个线程互换信息

*实例模拟服务生和顾客,服务生往空杯子中倒水,顾客从装满水的杯子中喝水,然后互换杯子,服务生接着倒水,顾客接着喝水.

*/

/**

*使用Exchanger的关键技术点如下:

*1.初始化Exchanger对象时,可以通过泛型指定杯子能交换的信息类型."newExchanger<String>;"表示只能交换String类型的信息

*2.Exchangerexchange方法表示当前线程准备交换信息,等待其他线程与它交换信息.当有其他线程调用该Exchanger对象的exchange方法时,立即交换信息

*/

publicclassExchangerTest {

//描述一个装水的杯子

publicstaticclassCup{

privatebooleanfull=false;//标识杯子是否有水

publicCup(booleanfull){

this.full= full;

}

//添水,假设需要5s

publicvoidaddWater(){

if(!this.full){

try{

Thread.sleep(5000);

}catch(InterruptedException e){

}

this.full=true;

}

}

//喝水,假设需要10s

publicvoiddrinkWater(){

if(this.full){

try{

Thread.sleep(10000);

}catch(InterruptedException e){

}

this.full=false;

}

}

}

publicstaticvoidtestExchanger(){

//初始化一个Exchanger,并规定可交换的信息类型是杯子

finalExchanger<Cup> exchanger =newExchanger<Cup>();

//初始化一个空的杯子和装满水的杯子

finalCup initialEmptyCup =newCup(false);

finalCup initialFullCup =newCup(true);

//服务生线程

classWaiterimplementsRunnable{

publicvoidrun(){

Cup currentCup = initialEmptyCup;

try{

inti = 0;

while(i < 2){

System.out.println("服务生开始往杯子里倒水: "+ System.currentTimeMillis());

//往空的杯子里倒水

currentCup.addWater();

System.out.println("服务生添水完毕: "+ System.currentTimeMillis());

//杯子满后和顾客的空杯子交换

System.out.println("服务生等待与顾客交换杯子: "+ System.currentTimeMillis());

currentCup = exchanger.exchange(currentCup);

System.out.println("服务生与顾客交换杯子完毕: "+ System.currentTimeMillis());

i++;

}

}catch(InterruptedException ex){

}

}

}

//顾客线程

classCustomerimplementsRunnable{

publicvoidrun(){

Cup currentCup= initialFullCup;

try{

inti = 0;

while(i < 2){

System.out.println("顾客开始喝水: "+ System.currentTimeMillis());

//把杯子里的水喝掉

currentCup.drinkWater();

System.out.println("顾客喝水完毕: "+ System.currentTimeMillis());

//将空杯子和服务生的满杯子交换

System.out.println("顾客等待与服务生交换杯子: "+ System.currentTimeMillis());

exchanger.exchange(currentCup);

System.out.println("顾客与服务生交换杯子完毕: "+ System.currentTimeMillis());

i++;

}

}catch(InterruptedException ex){

}

}

}

newThread(newWaiter()).start();

newThread(newCustomer()).start();

}

publicstaticvoidmain(String... args){

ExchangerTest.testExchanger();

}

}

/**

Waiter是模拟服务生的线程,首先往空杯子中添水,然后调用Exchangerexchange方法,等待和别人交换杯子.Customer是模拟了顾客的线程,首先把装满水的杯子喝光,然后调用Exchangeexchange方法,等待和别人交换杯子.当服务生和顾客都准备交换杯子时,Exchanger将服务生手中装满水的杯子和顾客手中的空杯子交换.服务生可以继续倒水,而顾客可以继续喝水.

*/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值