From: harry h. <har...@ho...> - 2007-09-05 22:22:25
|
Hi, I wrote a java Dining-Philosopher program and checked this program in the JPF. JPF says there are no deadlocks but the program still suffers from starvation. What is the best way to write the program so that there is no starvation and is there a way to use JPF to check not only for freedom from deadlock but also freedom from starvation? The Philosopher class and the Fork class and the Mian class are provided as below . ============== public class Philosopher extends Thread { private Fork left, right; private int status, id; private static final int IDLE = 0; private static final int THINKING = 1; private static final int HUNGRY = 2; private static final int EATING = 3; Philosopher(Fork l, Fork r, int an_id) { left = l; right = r; id = an_id; } public void run() { while (true) { try { think(); eat(left, right); } catch (InterruptedException e) { System.out.println(e); } } } public void think() { status = THINKING; status = HUNGRY; } public synchronized void eat(Fork l, Fork r) throws InterruptedException { left.grab(); //add: release the left folk if right folk is inused while (right.isInuse()) { left.release(); --- l1 left.grab(); --- l2 } right.grab(); --- l3 //ensure right and left folks are inused assert (right.isInuse() && left.isInuse()); status = EATING; System.out.println("PH " + id + " is eating"); left.release(); right.release(); status = IDLE; System.out.println("PH " + id + " is idle"); } } ================ public class Fork{ private boolean inuse; // new added private final ReentrantLock lock = new ReentrantLock(true); public synchronized void grab() throws InterruptedException { while (inuse) { try { wait(); } catch (InterruptedException e) { System.out.println(e); } } inuse = true; } public synchronized void release() throws InterruptedException { inuse = false; notify(); } public boolean isInuse() { return inuse; } } ============ public class DiningPhilosophers { // The number of philosophers public static final int COUNT = 3; public static void main(String args[]) { // Create the forks Fork[] forks = new Fork[COUNT]; for (int i=0; i<COUNT; i++) { System.out.println("Creating fork#: "+i); forks[i]=new Fork(); } // Create and start the Philosophers Philosopher[] philosophers = new Philosopher[COUNT]; for (int i=0; i<COUNT; i++) { System.out.println("Creating philosopher#: "+i); philosophers[i]=new Philosopher(forks[i], forks[(i+1)%COUNT], i); philosophers[i].start(); } } } ============= Regards, Hai _________________________________________________________________ Share your special parenting moments! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us |