-
Notifications
You must be signed in to change notification settings - Fork 0
/
CookFood.java
103 lines (94 loc) · 3.64 KB
/
CookFood.java
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package edu.OSU;
package java.lang.Object;
public class CookFood implements Runnable{
public int cookId;
public Diner servedDiner;
public int numBurgers, numFries, coke;
public void serveDiner() throws InterruptedException {
synchronized (App.hungryDiners) {
while (App.hungryDiners.isEmpty())
App.hungryDiners.wait();
servedDiner = App.hungryDiners.poll();
numBurgers = servedDiner.order.burgers_num;
numFries = servedDiner.order.fries_num;
coke = servedDiner.order.coke;
System.out.println(App.getTime() +" - Cook "+cookId+" processes Diner "+servedDiner.diner_id+"'s order.");
App.out.println(App.getTime() +" - Cook "+cookId+" processes Diner "+servedDiner.diner_id+"'s order.");
}
}
public void cook() throws InterruptedException {
while ((App.isBurgerMachineFree && numBurgers>0) || (App.isFriesMachineFree && numFries>0) ||
(App.isCokeMachineFree && coke==1)) {
if (App.isBurgerMachineFree && numBurgers>0) {
synchronized (App.burgerMachineLock) {
App.isBurgerMachineFree = false;
System.out.println(App.getTime() + " - Cook " + cookId + " is using the burger machine.");
}
Thread.sleep(5000);
synchronized (App.burgerMachineLock) {
--numBurgers;
App.isBurgerMachineFree = true;
App.burgerMachineLock.notify();
}
}
if (App.isFriesMachineFree && numFries>0) {
synchronized (App.friesMachineLock) {
App.isFriesMachineFree = false;
System.out.println(App.getTime() + " - Cook " + cookId + " is using the fries machine.");
}
Thread.sleep(3000);
synchronized ((App.friesMachineLock)) {
--numFries;
App.isFriesMachineFree = true;
App.friesMachineLock.notify();
}
}
if (App.isCokeMachineFree && coke>0) {
synchronized (App.cokeMachineLock) {
App.isCokeMachineFree = false;
System.out.println(App.getTime() + " - Cook " + cookId + " is using the coke machine.");
}
Thread.sleep(1000);
synchronized (App.cokeMachineLock) {
--coke;
App.isCokeMachineFree = true;
App.cokeMachineLock.notify();
}
}
if (!App.isBurgerMachineFree && numBurgers>0) {
synchronized (App.burgerMachineLock) {
App.burgerMachineLock.wait();
}
}
if (!App.isFriesMachineFree && numFries>0) {
synchronized (App.friesMachineLock) {
App.friesMachineLock.wait();
}
}
if (!App.isCokeMachineFree && coke==1) {
synchronized (App.cokeMachineLock) {
App.cokeMachineLock.wait();
}
}
}
}
public void orderReady() {
if ( (numBurgers + numFries + coke) == 0 ) {
synchronized (servedDiner) {
servedDiner.notify();
}
}
}
@Override
public void run() {
try {
while(true) {
serveDiner();
cook();
orderReady();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}