-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathPhilosopher.java
34 lines (30 loc) · 1.17 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
public class Philosopher implements Runnable {
private final Object leftFork;
private final Object rightFork;
Philosopher(Object left, Object right) {
this.leftFork = left;
this.rightFork = right;
}
private void doAction(String action) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " " + action);
Thread.sleep(((int) (Math.random() * 100)));
}
@Override
public void run() {
try {
while (true) {
doAction(System.nanoTime() + ": Thinking"); // thinking
synchronized (leftFork) {
doAction(System.nanoTime() + ": Picked up left fork");
synchronized (rightFork) {
doAction(System.nanoTime() + ": Picked up right fork - eating"); // eating
doAction(System.nanoTime() + ": Put down right fork");
}
doAction(System.nanoTime() + ": Put down left fork. Returning to thinking");
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}