-
Notifications
You must be signed in to change notification settings - Fork 5
/
TheDiningPhilosophers.java
41 lines (30 loc) · 1.12 KB
/
TheDiningPhilosophers.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
/*https://leetcode.com/problems/the-dining-philosophers/*/
class DiningPhilosophers {
Semaphore[] forks;
Semaphore philosophers;
public DiningPhilosophers() {
forks = new Semaphore[5];
for (int i = 0; i < 5; ++i)
forks[i] = new Semaphore(1);
philosophers = new Semaphore(1);
}
// call the run() method of any runnable to execute its code
public void wantsToEat(int philosopher,
Runnable pickLeftFork,
Runnable pickRightFork,
Runnable eat,
Runnable putLeftFork,
Runnable putRightFork) throws InterruptedException {
philosophers.acquire();
forks[philosopher].acquire();
forks[(philosopher+1)%5].acquire();
pickLeftFork.run();
pickRightFork.run();
eat.run();
putLeftFork.run();
putRightFork.run();
forks[philosopher].release();
forks[(philosopher+1)%5].release();
philosophers.release();
}
}