-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdining_philosopher.java
114 lines (85 loc) · 3.14 KB
/
dining_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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;
public class dining_philosopher {
static int philosopher = 5;
static Philosopher philosophers[] = new Philosopher[philosopher];
static Chopstick chopsticks[] = new Chopstick[philosopher];
static class Chopstick {
public Semaphore mutex = new Semaphore(1);
void grab() {
try {
mutex.acquire();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
void release() {
mutex.release();
}
boolean isFree() {
return mutex.availablePermits() > 0;
}
}
static class Philosopher extends Thread {
public int number;
public Chopstick leftchopstick;
public Chopstick rightchopstick;
Philosopher(int num, Chopstick left, Chopstick right) {
number = num;
leftchopstick = left;
rightchopstick = right;
}
public void run() {
while (true) {
leftchopstick.grab();
System.out.println("Philosopher " + (number + 1) + " grabs left chopstick.");
rightchopstick.grab();
System.out.println("Philosopher " + (number + 1) + " grabs right chopstick.");
eat();
leftchopstick.release();
System.out.println("Philosopher " + (number + 1) + " releases left chopstick.");
rightchopstick.release();
System.out.println("Philosopher " + (number + 1) + " releases right chopstick.");
}
}
void eat() {
try {
int sleepTime = ThreadLocalRandom.current().nextInt(0, 1000);
System.out.println("Philosopher " + (number + 1) + " eats for " + sleepTime + "ms");
Thread.sleep(sleepTime);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
public static void main(String args[]) {
for (int i = 0; i < philosopher; i++) {
chopsticks[i] = new Chopstick();
}
for (int i = 0; i < philosopher; i++) {
philosophers[i] = new Philosopher(i, chopsticks[i], chopsticks[(i + 1) % philosopher]);
philosophers[i].start();
}
while (true) {
try {
Thread.sleep(1000);
boolean deadlock = true;
for (Chopstick cs : chopsticks) {
if (cs.isFree()) {
deadlock = false;
break;
}
}
if (deadlock) {
Thread.sleep(1000);
System.out.println("Everyone Eats");
break;
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
System.out.println("Exit The Program!");
System.exit(0);
}
}