/**
 * Philosopher.java
 *
 * A possible solution to the Dining Philosopher Problem
 *  using semaphores.
 *
 * @author Jalal Kawash
 * @version 1.0 - February 2, 2001
 * 
 */


public final class Philosopher extends Thread {

    public Philosopher(int i, Semaphore l, Semaphore r) {
	/* assigns id for philosopher */
	id = i;
	LeftChopstick = l;
	RightChopstick = r;
    }

    private void entry() {
	if (id % 2 == 0) { /* even id philosopher */
		RightChopstick.P(); /* try to pick up the right chopstick */
		LeftChopstick.P(); /* left chopstick */
	    }
	    else { /* odd id philosopher */
		  LeftChopstick.P(); /* left chopstick first */
		  RightChopstick.P(); /* right chopstick */
	    }
    }

    private void exit() { /* release chopsticks */
	RightChopstick.V();
	LeftChopstick.V();
    }

    private void eat() {
	System.out.println("               Philosopher " + id + " is eating!");
	try {
	     Thread.sleep( (int) (Math.random() * 3000));
	}
	catch (InterruptedException e) {}
	System.out.println("               Philosopher " + id + " is full!");
    }

    private void think() {
	System.out.println("Philosopher " + id + " is thniknig!");
	try {
	     Thread.sleep( (int) (Math.random() * 3000));
	}
	catch (InterruptedException e) {}
    }
	
  
    public void run() {
	while(true) {
	    entry();
	    eat();
	    exit();
	    think();
	}
    }
 
private Semaphore LeftChopstick;
private Semaphore RightChopstick;
private int id;
}
     

