厨师 做菜 java_实验题目:用Java的等待/通知机制实现“厨师—食 者”问题。假设分别有4位厨师和6位食者。厨师做一盘 菜的时间为4s,食者吃一盘菜的时间为3s。编程实现这 一功能,参考“生产者...

该博客通过Java代码展示了如何使用等待/通知机制解决‘厨师—食者’问题。4位厨师每4秒制作一盘菜,6位食者每3秒消耗一盘菜。代码包括Food、Cook、Eater和Table类,Table类维护了一个最大容量的容器,确保了厨师和食者的同步操作。
摘要由CSDN通过智能技术生成

Food类

package cook_eat;

public class Food {

}

Cook类

package cook_eat;

public class Cook extends Thread{

private Table table;

public Cook(Table table) {

this.table = table;

}

@Override

public void run() {

while(true) {

// 做菜

Food food = new Food();

// 需要四秒

try {

Thread.sleep(4000);

} catch (Exception e) {

e.printStackTrace();

}

// 上菜

table.putFood(food);

}

}

}

Eater类

package cook_eat;

public class Eater extends Thread{

private Table table;

public Eater(Table table) {

this.table = table;

}

@Override

public void run() {

while(true) {

// 吃菜

Food food = table.getFood();

// 需要三秒

try {

Thread.sleep(3000);

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

Table类

package cook_eat;

import java.util.LinkedList;

class Table extends LinkedList {

int maxSize; // 容器的最大容量

public Table(int maxSize) {

this.maxSize = maxSize;

}

public synchronized void putFood(Food f) { // 向容器内放置食品

while (this.size() >= this.maxSize) {

try {

System.out.println("The table is too full,wait a moment!");

wait();

} catch (Exception e) {

}

}

this.addLast(f);

System.out.println("厨师上一份菜,现在桌上还有有"+this.size()+"份菜");

notifyAll();

}

public synchronized Food getFood() { // 从容器内取食品

Food f;

while (this.size() <= 0) {

try {

System.out.println("There is no food now ,come here later!");

wait();

} catch (Exception e) {

}

}

f = (Food) this.getFirst();

this.remove(f);

System.out.println("食客吃了一份菜,现在桌上有"+this.size()+"份菜");

notifyAll();

return f;

}

}

Test类

package cook_eat;

public class Test {

public static void main(String[] args) {

// 假定一开始桌上有六道菜

Table table = new Table(6);

// 厨师开始做菜

new Cook(table).start();

new Cook(table).start();

new Cook(table).start();

new Cook(table).start();

// 食客开始吃菜

new Eater(table).start();

new Eater(table).start();

new Eater(table).start();

new Eater(table).start();

new Eater(table).start();

new Eater(table).start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值