-
Notifications
You must be signed in to change notification settings - Fork 1
/
1226.DiningPhilosophers.java
47 lines (40 loc) · 1.19 KB
/
1226.DiningPhilosophers.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
```
class DiningPhilosophers
{
private Lock forks[] = new Lock[5];
private Semaphore semaphore = new Semaphore(4);
public DiningPhilosophers()
{
for (int i = 0; i < 5; i++)
forks[i] = new ReentrantLock();
}
void pickFork(int id, Runnable pick)
{
forks[id].lock();
pick.run();
}
void putFork(int id, Runnable put)
{
put.run();
forks[id].unlock();
}
// 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
{
int leftFork = philosopher;
int rightFork = (philosopher + 4) % 5;
semaphore.acquire();
pickFork(leftFork, pickLeftFork);
pickFork(rightFork, pickRightFork);
eat.run();
putFork(rightFork, putRightFork);
putFork(leftFork, putLeftFork);
semaphore.release();
}
}
```