
(code source of file Philosopher.java) 


import java.util.concurrent.Semaphore;


public class Philosopher  extends Thread{

	private int PhilosopherId; 
		//PhilosopherId

	static final int nrMinIterations =12;
		//1000

	static final long timeMinPerIteration= 3000000000l;
		//ns => 3 seconds...
		
	static final int nrTotalPhilosophers=5;

	static final int  maxNrPhilosophersEating =
		 (int) (nrTotalPhilosophers/2);

	static int nrPhilosophersEating =0; 
		// nr Philosophers eating (now)

	static int nrThreadsFinished =0; 	
		// nr Philosophers finished (now)
	
	boolean eating = false; 
	// true= yes; false= no (not eating) => thinks

	final boolean EATING = true; 
	final boolean THINKING = false;
	
	final private static int minThinkTime =500; 
	//ms

	final private static int thinkTime = 1200; 
	//ms

	final private static int minPauseMeal = 500; 
	//ms

	final private static int varPauseMeal = 700; 
	//ms

	private static Semaphore s  = 
	new Semaphore(maxNrPhilosophersEating);	

	private static Semaphore mutex  = new Semaphore(1);	
		// to access shared var nrPhilosophersEating

	private static Semaphore efficientSummarySem  = new Semaphore(0); 
	//syncro sem (optional practice)

	private Philosopher leftPh, rightPh;

	private int nrMeals = 0;

	private int nrIterations=0;

	private long timeSpent=0l;
	
	
	public Philosopher(int i ) { 		
		
		// constructor
		PhilosopherId=i;	
		setLeftPh(null);	
		setRightPh(null);
	}
	

	// getters and setters

	
	public int getNrIterations() {
		return nrIterations;	}


	public void setNrIterations(int i) {	
		this.nrIterations = i;}

	
	public long getTimeSpent() {
		return timeSpent;}


	public void setTimeSpent(long timeSpent) {
		this.timeSpent = timeSpent;}

	
	public static int getNrThreadsFinished() {
		return nrThreadsFinished;}

	public static void setNrThreadsFinished(int nrPhFinished) {	
		nrThreadsFinished = nrPhFinished;
	}
	

	public int getNrMeals() {
		return nrMeals;}


	public void setNrMeals(int nrMeals) {
		this.nrMeals = nrMeals;}

	
	public Philosopher getLeftPh() {
		return leftPh;}


	public void setLeftPh(Philosopher leftPh) { 
		this.leftPh = leftPh;}


	public Philosopher getRightPh() {	
		return rightPh;	}


	public void setRightPh(Philosopher rightPh) {
		this.rightPh = rightPh;}


	public static int getNrPhilosophersEating() {
		return nrPhilosophersEating;	}

	public static void setNrPhilosophersEating( 
				int nrPhilosophersEating) {
		Philosopher.nrPhilosophersEating = nrPhilosophersEating;	}

		
	public int getPhilosopherId() {
		return PhilosopherId;}


	public void setPhilosopherId(int id) {
		this.PhilosopherId = id;}

	
	public boolean isEating() {
		return eating;}


	public void setEating(boolean eating) {
		this.eating = eating;}

		
	static int getLeftPhilosopherId(int i){ 
		return (int) ( (i - 1 + 
		nrTotalPhilosophers) % nrTotalPhilosophers );}


	static int getRightPhilosopherId(int i){ 
		return (int) ((i+1) % nrTotalPhilosophers );}

		
	private static void initData() {

		System.out.println ("**************** Philosophers ********************* \n");
		System.out.println (" Nr Philosophers = " +  nrTotalPhilosophers + ".");
		System.out.println (" Max Nr Philosophers Eating (at same time) = " + 					maxNrPhilosophersEating +".\n");			
	}
	 
	
	private void philosopherThinks(int time, int iterations) { 

		int thinks;
		thinks = (int) (minThinkTime + Math.random()*time);
		
		System.out.print ("\n Phil_id:" + getPhilosopherId() + 
			" begins thinking " + thinks +
			" ms. NrPhilsEating:" + getNrPhilosophersEating() + 
			". Eats?:" + this.isEating() + 	". Meals: *" + 
			getNrMeals() + "*. Count: " +  iterations + ".");
		
		try {Thread.sleep(thinks);} 
		catch(InterruptedException e) {};	
	}
	
	
	private void philosopherEats(){

		int eatTime;
		eatTime = minPauseMeal + 
			(int)(Math.random() * varPauseMeal);

		setNrMeals(getNrMeals() + 1);

		System.out.print ("\n Phil_id:" + getPhilosopherId() + 
		" begins eating: " + eatTime + " ms. Meals: "+getNrMeals() + 
		". NrPhilsEating:" + getNrPhilosophersEating() + 
		". Eats?:"+this.isEating() + ".");
				 
		try {Thread.sleep(eatTime);} 
		catch(InterruptedException e) {};	
	}

	
	private void displayCantEat() {

	  System.out.println ("\n Phil_id:" + getPhilosopherId() + 
	 	 " CAN'T EAT ... Meals: " + getNrMeals() + ". NrPhilsEating:" + 
		getNrPhilosophersEating() +  ". Eats? " +  this.isEating() + 
		". LeftPh :" + getLeftPh().getPhilosopherId() + " Eats? " + 
	  	getLeftPh().isEating()  + ". RightPh :" + getRightPhilosopherId(getPhilosopherId()) + 
	 	 " Eats? " + getRightPh().isEating() + ".");
	}
	
	
	
	private boolean triesToEat() {

		boolean  leftPhilosopherEats,rightPhilosopherEats;
		
	if (getNrPhilosophersEating() >= maxNrPhilosophersEating) {
		//optimization

		 displayCantEat();   return false; 

	}	// no semaphores needed => thinks (sleeps)
		
	 try {mutex.acquire();}
	catch(InterruptedException e) {};
	  
	leftPhilosopherEats = getLeftPh().isEating();

	rightPhilosopherEats= getRightPh().isEating();
	  	 
	if((! leftPhilosopherEats)&&(!rightPhilosopherEats)) {

		try {s.acquire();}
		catch(InterruptedException e) {};

		this.setEating(EATING);

		setNrPhilosophersEating(getNrPhilosophersEating()+1);

		mutex.release();

		philosopherEats();

		try {mutex.acquire();}
		catch(InterruptedException e) {};

		this.setEating(THINKING);

		setNrPhilosophersEating(getNrPhilosophersEating() - 1);

		mutex.release();
		s.release();
		 return true; 
	}
	else { 
		mutex.release();  
		displayCantEat();   
		return false;
	}
		
	} // end triesToEat()

	
	
	private int antiStarvationCorrection(boolean eats) {
		return eats? 2*thinkTime : (int) (thinkTime/3);}
	
	
	private synchronized void summary( long timeSpent, int i) {
		setNrThreadsFinished(getNrThreadsFinished() + 1);
		setNrIterations(i); 
		setTimeSpent(timeSpent);

		System.out.print ("\n ***	PhilosopherId:" + 
		getPhilosopherId() + " finished. Nr of meals: " + getNrMeals()
		+". Threads finished: " + getNrThreadsFinished() + ". Spent: " +  						(int) (timeSpent/1000000) + "ms. Loops: " + i + ".	***");
		
		if (getNrThreadsFinished() == nrTotalPhilosophers)
		// syncro with main (optional exercise)
			efficientSummarySem.release();
	}

	
	public void run() {
		
		int moreChances; 
		// anti Starvation corrections

		boolean eats= false;
		long ellapsed, timeSpent=0l; 
		int i=0;

		long begin = System.nanoTime();
		// anti Starvation correction => min time

		while (timeSpent < nrMinIterations * timeMinPerIteration) {
		// or: while true

			moreChances = antiStarvationCorrection(eats);							
			philosopherThinks(moreChances,i); 
	
			eats= triesToEat();
	
			ellapsed = System.nanoTime();
	
			timeSpent = (long) (ellapsed  begin); i ++;
		}
		summary(timeSpent,i);
	}
	

	public static void main(String[] args) {
			
		initData();
		
		Philosopher  [] p = new Philosopher [nrTotalPhilosophers];
		
		for(int i = 0; i < nrTotalPhilosophers; i ++) { 
			p[i]=new Philosopher (i);}
		
		for(int i = 0; i < nrTotalPhilosophers; i ++) { 

			p[i].setLeftPh(p[getLeftPhilosopherId(i)]);
			p[i].setRightPh(p[getRightPhilosopherId(i)]);
			p[i].start();	
		}
		
		for(int i = 0; i < nrTotalPhilosophers; i ++) { 
			System.out.println (" PhilosopherId:" + i + " LeftPhId:" + 							getLeftPhilosopherId(i) + " RightPhId:" + getRightPhilosopherId(i) + ".");			
		}	// end for	
		
		//blocks here... until all philosophers finish... optional thread practice

		try {efficientSummarySem.acquire();}
		catch(InterruptedException e) {};
		
		System.out.println ("\n**************** Philosophers Final Summary********************* ");
		System.out.println ("	Nr of Threads finished: " + 
			getNrThreadsFinished() + ".	***\n\n");
		
		for(int i=0;i< nrTotalPhilosophers;i++) {

			try {p[i].join();}
			catch(InterruptedException e) {};
			
			System.out.println (" ***	 Philos_" + i + " Ended/joined. Nr of meals: *" + 
			p[i].getNrMeals() + "*. NrIterations: " + p[i].getNrIterations() + ". Spent: " +  				(int)(p[i].getTimeSpent()/1000000) + "ms.	***");
			
		} 
		// end for => Main() waits that all threads finish.

		System.exit(0);
		
	}//end main

}// end class
