/** * A class to hold the forks in the dining philosphers problem. * This class acts as a monitor to control the allocation of forks. * * @author Scot Drysdale */ public class ForksMonitor { public boolean [] forks; // True indicates that the fork is taken /** * Construct a object with num forks. * Mark all as not in use. * @param num number of forks (and philosophers) */ public ForksMonitor(int num) { forks = new boolean[num]; for(int i = 0; i < forks.length; i++) forks[i] = false; } /** * Pick up forks numbered pNum and pNum+1 (wrapping). * Block if either fork is in use. * pNum the number of the first fork */ public synchronized void pickUpForks(int pNum) throws InterruptedException { // If either fork is in use wait while (forks[pNum] || forks[(pNum+1) % forks.length] ) wait(); // Take the forks forks[pNum] = true; forks[(pNum+1) % forks.length] = true; } /** * Put down forks numbered pNum and pNum+1 (wrapping). * Assumes that this philosopher had been granted the forks. * pNum the number of the first fork */ public synchronized void putDownForks(int pNum) throws InterruptedException { // Put down the forks forks[pNum] = false; forks[(pNum+1) % forks.length] = false; notifyAll(); } }