-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChef.java
More file actions
64 lines (52 loc) · 1.39 KB
/
Chef.java
File metadata and controls
64 lines (52 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package Thread.ProductAndResumer;
import java.util.concurrent.TimeUnit;
/*
* 生产者消费者模型有四个对象:
* 生产者(chef)
* 消费者(waiter)
* 仓库(resturant)
* 产品(meal)
*
* 此例展示单个产品的生产者与消费者
* 生产者
*
* */
public class Chef implements Runnable {
private Resturant resturant;
private int num = 0;
public Chef(Resturant resturant) {
this.resturant = resturant;
}
public void run() {
try{
while (!Thread.interrupted()) {
// 1.检查餐厅中是否有食物,没有食物,chef自己进入等待状态
synchronized (this) {
while (resturant.meal!= null) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//2.设置食物超过十号,代表食材用完
if(++num==4){
System.out.println("食物已经卖完");
resturant.executorService.shutdownNow();
}
System.out.println("订单已经到达厨房");
//4.生产食物的时间
TimeUnit.MILLISECONDS.sleep(100);
//3.生产完食物,通知waiter线程可以取餐
synchronized (resturant.waiter) {
resturant.meal=new Meal(num);
resturant.waiter.notifyAll();
}
}
}catch(InterruptedException e){
System.out.println("厨师线程结束");
}
}
}