0%

1226-哲学家进餐

前言:学习JUC包后,通过leetcode多线程的题目练习一下,1226-哲学家进餐

Semaphore + ReentrantLock

最多允许4个哲学家就餐

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
public class DiningPhilosophers {
private Semaphore max = new Semaphore(4);
private ReentrantLock[] forkLocks = new ReentrantLock[5];

public DiningPhilosophers() {
for (int i = 0; i < 5; i++) {
forkLocks[i] = new ReentrantLock();
}
}

public void wantsToEat(int philosopher,
Runnable pickLeftFork,
Runnable pickRightFork,
Runnable eat,
Runnable putLeftFork,
Runnable putRightFork) throws InterruptedException {
max.acquire();
// 拿起左边叉子
forkLocks[(philosopher + 1) % 5].lock();
pickLeftFork.run();
// 拿起右边叉子
forkLocks[philosopher].lock();
pickRightFork.run();
// 吃
eat.run();
// 放下左边叉子
putLeftFork.run();
forkLocks[(philosopher + 1) % 5].unlock();
// 放下右边叉子
putRightFork.run();
forkLocks[philosopher].unlock();
max.release();
}
}
-------------本文结束感谢您的阅读-------------