Meal,WaitPerson and Chef using Lock and Condition

本文深入探讨了使用Java并发控制技术实现餐厅系统中厨师与等待人员之间的高效交互。通过创建MealCS、WaitPersonCS和ChefCS类,展示了如何利用锁和条件变量确保线程安全地分配食物,模拟现实世界中的餐厅场景。

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

import java.util.concurrent.locks.*;

class MealCS {
    private final int orderNum	;
    public MealCS(int num) {
        this.orderNum=num;
    }
    public String toString() {
        return " MealCS "+orderNum;
    }

}
class WaitPersonCS implements Runnable {
    private Lock lock;
    private Condition condition;
    private int count;
    public WaitPersonCS(Lock lock,Condition condition,int count) {
        this.lock=lock;
        this.condition=condition;
        this.count=count;
    }

    public void run() {
        try {
            while(count-->0) {
                lock.lock();
                try{
                    while(RestaurantCS.MEAL==null)
                        condition.await();
                    System.out.println("The WaitPersonCS has eaten " + RestaurantCS.MEAL);
                    RestaurantCS.MEAL=null;
                   condition.signal();
               
                    
                }finally{
                	
                	lock.unlock();
                }
            }
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }

}
class ChefCS implements Runnable {
    private Lock lock;
    private Condition condition;
    private int count;
    public ChefCS(Lock lock,Condition condition,int count) {
        this.lock=lock;
        this.condition=condition;
        this.count=count;
    }

    public void run() {
        try {
            while(count-->0) {
                 lock.lock();
                try{
                    while(RestaurantCS.MEAL!=null)
                       condition.await();
                    RestaurantCS.MEAL=new MealCS(count);
                    System.out.println("The ChefCS has made  " + RestaurantCS.MEAL);
                    condition.signal();
                }finally{
                	
                	lock.unlock();
                }
            }
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }

}

public class RestaurantCS {
    public static MealCS MEAL;

    public static void main(String[] args) throws Exception {
        Lock lock=new ReentrantLock();
        Condition condition=lock.newCondition();
        new Thread(new ChefCS(lock,condition,10)).start();
        new Thread(new WaitPersonCS(lock,condition,10)).start();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值