import java.util.Random; /** * Solves the dining philosophers problem * * @author Scot Drysdale */ public class PhilosopherMonitor extends Thread { private int myNum; // Number of this philosopher private ForksMonitor forks; private Random generator; private static final int EAT_TIME = 1000; private static final int THINK_TIME = 1000; private static final int NUM_MEALS = 10; private static final int NUM_PHILOSOPHERS = 6; public PhilosopherMonitor(int philNum, ForksMonitor theForks) { myNum = philNum; forks = theForks; generator = new Random(); } /** * Eat using a monitor to control the forks * * @param meal * the number of the meal eaten */ public void eat(int meal) throws InterruptedException { System.out.println("Philosopher " + myNum + " trys to pick up forks"); forks.pickUpForks(myNum); System.out.println("Philosopher " + myNum + " picks up forks and eats meal " + meal); sleep(EAT_TIME + generator.nextInt(EAT_TIME)); System.out.println("Philosopher " + myNum + " puts down forks and thinks"); forks.putDownForks(myNum); sleep(THINK_TIME + generator.nextInt(THINK_TIME)); } /** * The code to eat NUM_MEALS meals is in the run method of the thread. */ public void run() { try { for (int meal = 1; meal <= NUM_MEALS; meal++) eat(meal); } catch (InterruptedException e) { } } /** * Create NUM_PHILOSOPHERS philosopher threads and start them eating */ public static void main(String[] args) { ForksMonitor forks = new ForksMonitor(NUM_PHILOSOPHERS); for (int num = 0; num < NUM_PHILOSOPHERS; num++) { PhilosopherMonitor phil = new PhilosopherMonitor(num, forks); phil.start(); } } }