用Java的等待/通知机囤实现‘厨师-食囨’问题,假设分别有6位厨师和6位食囨。厨师做団盘菜的时间为4s,食囨吃団盘菜的时间为3s。编程实现这団囧能,参考“囥囦囨-消费囨”问题。
时间: 2023-05-20 11:01:00 浏览: 129
好的,让我来回答你的问题。以下是Java的等待/通知机制实现‘厨师-食客’问题的代码:
```
public class ChefCustomerProblem {
public static void main(String[] args) {
Restaurant restaurant = new Restaurant();
Chef[] chefs = new Chef[6];
Customer[] customers = new Customer[6];
for (int i = 0; i < 6; i++) {
chefs[i] = new Chef(restaurant);
customers[i] = new Customer(restaurant);
chefs[i].start();
customers[i].start();
}
}
}
class Restaurant {
private int dishCount = 0;
private final int MAX_DISH_COUNT = 10;
public synchronized void makeDish() throws InterruptedException {
while (dishCount == MAX_DISH_COUNT) {
wait();
}
dishCount++;
System.out.println("厨师做了一道菜,当前菜品数量:" + dishCount);
notifyAll();
}
public synchronized void eatDish() throws InterruptedException {
while (dishCount == 0) {
wait();
}
dishCount--;
System.out.println("食客吃了一道菜,当前菜品数量:" + dishCount);
notifyAll();
}
}
class Chef extends Thread {
private Restaurant restaurant;
public Chef(Restaurant restaurant) {
this.restaurant = restaurant;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(4000);
restaurant.makeDish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Customer extends Thread {
private Restaurant restaurant;
public Customer(Restaurant restaurant) {
this.restaurant = restaurant;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(3000);
restaurant.eatDish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个程序中,Restaurant类代表餐厅,其中makeDish()方法表示厨师做菜,eatDish()方法表示食客吃菜。Chef类表示厨师,Customer类表示食客。在程序中,使用了Java的等待/通知机制来实现厨师和食客之间的协作。当菜品数量达到最大值时,厨师会等待,直到有食客吃掉一道菜;当菜品数量为0时,食客会等待,直到有厨师做出一道菜。这样就能保证餐厅中的菜品数量始终在一个合理的范围内。
阅读全文