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();
}
}