实现服务生和顾客喝水(多线程编程)

本文通过Java的Exchanger类模拟服务生为顾客添水和顾客喝水的过程,展示了多线程间如何协调交换资源。服务生线程往空杯中加水,顾客线程从满杯中喝水,使用Exchanger实现杯子的交换,确保服务生和顾客的顺序执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

package book.j2se5;

import java.util.concurrent.Exchanger;

//模拟服务生和顾客,服务生往空杯子中倒水,顾客从装满水的杯子喝水,然后换杯子
//服务生接着喝水
public class ExchangerTest {

 //描述一个装水的杯子
 public static class Cup{
  private boolean full=false;//标识杯子是否有水
  public Cup(boolean full){
   this.full=full;
  }
  //添水,假定需要5s
  public void addWater(){
   if(!this.full){
    try{
     Thread.sleep(5000);
    }catch(InterruptedException e){
     
    }
    this.full=true;
   }
  }
  //喝水,假设需要10s
  public void drinkWater(){
   if(this.full){
    try{
     Thread.sleep(10000);
    }catch(InterruptedException e){
     
    }
    this.full=false;
   }
  }
 }
 public static void testExchanger(){
  //初始化一个Exchanger,并规定可交换的信息类型是杯子
  final Exchanger<Cup> exchanger=new Exchanger<Cup>();
  //初始化一个空的杯子和装满水的杯子
  final Cup initialEmptyCup=new Cup(false);
  final Cup initialFullCup=new Cup(true);
  //服务生线程
  class Waiter implements Runnable{
   public void run(){
    Cup currentCup=initialEmptyCup;
    try{
     int i=0;
     while(i<2){
      System.out.println("服务生开始往杯子中添水:"+System.currentTimeMillis());
      //往空杯子里面加水
      currentCup.addWater();
      System.out.println("服务生等待与顾客交换杯子:"+System.currentTimeMillis());
      currentCup=exchanger.exchange(currentCup);
      System.out.println("服务生与顾客交换杯子完毕:"+System.currentTimeMillis());
      i++;
     }
    }catch(InterruptedException ex){
     
    }
   }
  }
  class Customer implements Runnable{

   public void run() {
    Cup currentCup=initialFullCup;
    try{
     int i=0;
     while(i<2){
      System.out.println("顾客开始喝水:"+System.currentTimeMillis());
      currentCup.drinkWater();
      System.out.println("顾客喝水完毕:"+System.currentTimeMillis());
      System.out.println("顾客等待与服务生交换杯子:"+System.currentTimeMillis());
      currentCup=exchanger.exchange(currentCup);
      System.out.println("顾客与服务生交换杯子完毕:"+System.currentTimeMillis());
      i++;
     }
    }catch(InterruptedException ex){
     
    }
   }
  }
  new Thread(new Waiter()).start();
  new Thread(new Customer()).start();
 }
 public static void main(String[] args) {
  ExchangerTest.testExchanger();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值