哲学家进餐问题
5 个沉默寡言的哲学家围坐在圆桌前,每人面前一盘意面。叉子放在哲学家之间的桌面上。(5 个哲学家,5 根叉子)
所有的哲学家都只会在思考和进餐两种行为间交替。哲学家只有同时拿到左边和右边的叉子才能吃到面,而同一根叉子在同一时间只能被一个哲学家使用。每个哲学家吃完面后都需要把叉子放回桌面以供其他哲学家吃面。只要条件允许,哲学家可以拿起左边或者右边的叉子,但在没有同时拿到左右叉子时不能进食。
假设面的数量没有限制,哲学家也能随便吃,不需要考虑吃不吃得下。
设计一个进餐规则(并行算法)使得每个哲学家都不会挨饿;也就是说,在没有人知道别人什么时候想吃东西或思考的情况下,每个哲学家都可以在吃饭和思考之间一直交替下去。
信号量+可重入式锁
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
|
class DiningPhilosophers {
Semaphore semaphore = new Semaphore(4);
private static final ReentrantLock[] LOCKS = { new ReentrantLock(), new ReentrantLock(), new ReentrantLock(), new ReentrantLock(), new ReentrantLock() };
public void wantsToEat(int philosopher, Runnable pickLeftFork, Runnable pickRightFork, Runnable eat, Runnable putLeftFork, Runnable putRightFork) throws InterruptedException {
semaphore.acquire(); int nextPhilosopher = (philosopher + 1) % 5; LOCKS[philosopher].lock(); LOCKS[nextPhilosopher].lock();
pickLeftFork.run(); pickRightFork.run(); eat.run(); putLeftFork.run(); putRightFork.run();
LOCKS[philosopher].unlock(); LOCKS[nextPhilosopher].unlock(); semaphore.release(); } }
|
信号量+synchronized
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
|
class DiningPhilosophers {
Semaphore semaphore = new Semaphore(4);
private static final Object[] LOCKS = { new Object(), new Object(), new Object(), new Object(), new Object() };
public void wantsToEat(int philosopher, Runnable pickLeftFork, Runnable pickRightFork, Runnable eat, Runnable putLeftFork, Runnable putRightFork) throws InterruptedException {
semaphore.acquire(); int nextPhilosopher = (philosopher + 1) % 5; synchronized (LOCKS[philosopher]) { synchronized (LOCKS[nextPhilosopher]) { pickLeftFork.run(); pickRightFork.run(); eat.run(); putLeftFork.run(); putRightFork.run(); } } semaphore.release(); }
}
|