-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.java
74 lines (68 loc) · 1.99 KB
/
Main.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
import java.util.concurrent.*;
// There are 5 philosophers sitting around a
// table. Each philosopher thinks, or when hungry
// eats. Each philosopher has a bowl of noodles,
// but there are only 5 forks between each
// philosopher. However, in order to eat, a
// philosopher needs both forks. A deadlock occurs
// when all philosophers pick up one fork, but are
// waiting for the other fork to be put down.
// One idea to solve the dependency cycle is to
// alter the order in which the last philosopher
// picks up forks.
class Main {
static Thread[] philosopher;
static Semaphore[] fork;
static int N = 5;
// philosopher: all N philosophers
// fork: N forks placed between them
// N: number of philosophers
// 1. Think (sleep 100ms)
// 2. Pick left fork (i) (or wait)
// 3. Pick right fork (i+1) (or wait)
// 4. Eat (sleep 100ms)
// 5. Put back right fork
// 6. Put back left fork
// ...
// EXCEPT the last philospher, who instead
// picks up his right fork first; this is
// what helps us to avoid deadlock.
static Thread philosopher(int i) {
return new Thread(() -> {
try {
while(true) {
log(i+": thinking");
Thread.sleep(100);
int j = (i+1) % N;
int p = Math.min(i, j);
int q = Math.max(i, j);
fork[p].acquire();
fork[q].acquire();
log(i+": eating");
Thread.sleep(100);
fork[q].release();
fork[p].release();
}
}
catch (InterruptedException e) {}
log("ERROR: "+i+" stopped");
});
}
// 1. Forks are placed
// 2. Philosophers are seated
// 3. All philosophers now get to work
public static void main(String[] args) {
log(N+" philosophers get to work ...");
philosopher = new Thread[N];
fork = new Semaphore[N];
for(int i=0; i<N; i++) {
philosopher[i] = philosopher(i);
fork[i] = new Semaphore(1);
}
for(int i=0; i<N; i++)
philosopher[i].start();
}
static void log(String x) {
System.out.println(x);
}
}