-
Notifications
You must be signed in to change notification settings - Fork 0
/
Philosopher.java
91 lines (79 loc) · 2.39 KB
/
Philosopher.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
import common.BaseThread;
public class Philosopher extends BaseThread {
/**
* Max time an action can take (in milliseconds)
*/
public static final long TIME_TO_WASTE = 1000;
public void eat() {
try {
System.out.println("Philosopher " + getTID() + " is eating.");
Philosopher.yield();
sleep((long) (Math.random() * TIME_TO_WASTE));
Philosopher.yield();
System.out.println("Philosopher " + getTID() + " is finished eating.");
} catch (InterruptedException e) {
System.err.println("Philosopher.eat():");
DiningPhilosophers.reportException(e);
System.exit(1);
}
}
public void think() {
try {
System.out.println("Philosopher " + getTID() + " is thinking.");
Philosopher.yield();
sleep((long) (Math.random() * TIME_TO_WASTE));
Philosopher.yield();
System.out.println("Philosopher " + getTID() + " is finished thinking.");
} catch (InterruptedException e) {
System.err.println("Philosopher.think():");
DiningPhilosophers.reportException(e);
System.exit(1);
}
}
public void talk() {
try {
System.out.println("Philosopher " + getTID() + " is talking.");
Philosopher.yield();
saySomething();
Philosopher.yield();
System.out.println("Philosopher " + getTID() + " is finished talking.");
} catch (Exception e) {
System.err.println("Philosopher.talk():");
DiningPhilosophers.reportException(e);
System.exit(1);
}
}
/**
* No, this is not the act of running, just the overridden Thread.run()
*/
public void run() {
for (int i = 0; i < DiningPhilosophers.DINING_STEPS; i++) {
DiningPhilosophers.soMonitor.pickUp(getTID());
eat();
DiningPhilosophers.soMonitor.putDown(getTID());
think();
/*
* The program will randomly decide if the given
* philospher will talk or not.
*/
if (Math.random() < 0.5) {
DiningPhilosophers.soMonitor.requestTalk();
talk();
DiningPhilosophers.soMonitor.endTalk();
}
Thread.yield();
}
}
public void saySomething() {
String[] astrPhrases = {
"Eh, it's not easy to be a philosopher: eat, think, talk, eat...",
"You know, true is false and false is true if you think of it",
"2 + 2 = 5 for extremely large values of 2...",
"If thee cannot speak, thee must be silent",
"My number is " + getTID() + ""
};
System.out.println(
"Philosopher " + getTID() + " says: " +
astrPhrases[(int) (Math.random() * astrPhrases.length)]);
}
}