Repository navigation
Expand file tree
/
Copy pathDiningPhilospher.java
More file actions
73 lines (60 loc) · 1.61 KB
/
Copy pathDiningPhilospher.java
File metadata and controls
73 lines (60 loc) · 1.61 KB
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
import java.util.concurrent.*;
public class DiningPhilospher {
public static void main(String[] args) throws InterruptedException {
DiningPhilospherImp.startPhilospherLife();
}
}
class DiningPhilospherImp {
Semaphore[] forks = new Semaphore[5];
int noOfPhilosphers = 5;
private Semaphore maxDiners = new Semaphore(4); // to avoid deadlocks
public DiningPhilospherImp() {
forks[0] = new Semaphore(1);
forks[1] = new Semaphore(1);
forks[2] = new Semaphore(1);
forks[3] = new Semaphore(1);
forks[4] = new Semaphore(1);
}
void contemplate(int id) throws InterruptedException {
System.out.println("Philospher " + id + " contemplating");
Thread.sleep(1000);
}
void eat(int id) throws InterruptedException {
maxDiners.acquire();
forks[id].acquire();
forks[(id + 1)%5].acquire();
System.out.println("Philospher " + id + " is eating currently");
Thread.sleep(5000);
forks[id].release();
forks[(id + 1)%5].release();
maxDiners.release();
}
void lifeOfPhilospher(int id) throws InterruptedException {
while(true) {
contemplate(id);
eat(id);
}
}
public static void startPhilospherLife() throws InterruptedException {
DiningPhilospherImp dp = new DiningPhilospherImp();
Thread[] threads = new Thread[5];
for (int i=0; i < 5; i++) {
final int a = i;
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
try {
dp.lifeOfPhilospher(a);
} catch (InterruptedException e) {
}
}
});
}
for (int i=0; i < 5; i++) {
threads[i].start();
}
for (int i=0; i < 5; i++) {
threads[i].join();
}
}
}