前言:学习JUC包后,通过leetcode多线程的题目练习一下,1226-哲学家进餐
Semaphore + ReentrantLock
最多允许4个哲学家就餐
| 12
 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();
 }
 }
 
 |