|
| 1 | +class DiningPhilosophers { |
| 2 | + |
| 3 | + private List<Semaphore> forks; |
| 4 | + private Semaphore dinersOnTable; |
| 5 | + private List<String> state; |
| 6 | + |
| 7 | + public DiningPhilosophers() { |
| 8 | + this.forks = new ArrayList<>(); |
| 9 | + this.state = new ArrayList<>(); |
| 10 | + for (int i = 0; i < 5; i++) { |
| 11 | + this.forks.add(new Semaphore(1)); |
| 12 | + this.state.add("idle"); |
| 13 | + } |
| 14 | + this.dinersOnTable = new Semaphore(4); |
| 15 | + } |
| 16 | + |
| 17 | + // call the run() method of any runnable to execute its code |
| 18 | + public void wantsToEat(int philosopher, |
| 19 | + Runnable pickLeftFork, |
| 20 | + Runnable pickRightFork, |
| 21 | + Runnable eat, |
| 22 | + Runnable putLeftFork, |
| 23 | + Runnable putRightFork) throws InterruptedException { |
| 24 | + int leftForkIdx = philosopher; |
| 25 | + int rightForkIdx = (philosopher + 4) % 5; |
| 26 | + |
| 27 | + this.dinersOnTable.acquire(); |
| 28 | + if (this.state.get(philosopher).equals("eating")) { |
| 29 | + this.dinersOnTable.release(); |
| 30 | + return; |
| 31 | + } |
| 32 | + this.state.set(philosopher, "eating"); |
| 33 | + pickFork(leftForkIdx, pickLeftFork); |
| 34 | + pickFork(rightForkIdx, pickRightFork); |
| 35 | + eat.run(); |
| 36 | + putFork(rightForkIdx, putRightFork); |
| 37 | + putFork(leftForkIdx, putLeftFork); |
| 38 | + this.state.set(philosopher, "idle"); |
| 39 | + this.dinersOnTable.release(); |
| 40 | + } |
| 41 | + |
| 42 | + private void putFork(int idx, Runnable put) { |
| 43 | + put.run(); |
| 44 | + this.forks.get(idx).release(); |
| 45 | + } |
| 46 | + |
| 47 | + private void pickFork(int idx, Runnable pick) throws InterruptedException { |
| 48 | + this.forks.get(idx).acquire(); |
| 49 | + pick.run(); |
| 50 | + } |
| 51 | +} |
0 commit comments