/*
 * PhilosopherObs.java (Implements Philosopher using Event Notification.)
 *
 * Written By : Nitin Jeevan Motgi (nmotgi@cs.ucf.edu)
 *
 * Implements Event Notification in DP.
 *
 * Portions copyright(c) 2001 to School of Electrical Engineering and
 * Computer Science, UCF, Orlando.
 *
 * Use and distribution of this source code are strictly governed by
 * terms and conditions set by the author.
 *
 * Revision History Revisited.
*/

import java.util.*;
import java.lang.*;

/*****************************************************************************
 * This class basically simulates philosopher requests for eating using
 * Monitors. Basically it will make a request to acquire the lock before
 * eating. Once, the request gets into the queue it will make an attempt
 * to enter eating stage were it will pick forks and eat and also release
 * them after eating.
*****************************************************************************/
class PhilosopherObs extends Thread implements Observer{
  public int  nID;                      /* Indiviual Philosopher ID.*/
  private DiningPhilosopherObs DPhil;   /* Back Reference to higher class.*/         
  private boolean bEndCondition;        /* End Condition indicator.*/         
  private boolean bModified;
  
  /* This is default constructor for PhilosopherObs.*/
  PhilosopherObs(int nID,DiningPhilosopherObs DPhil){
    this.nID = nID;
    this.DPhil = DPhil;
    bEndCondition = true;               /* Initially set to true.*/
    bModified = false;
  }/* End of PhilosopherObs.*/

  /* Handler for message sent by the Observable.*/
  public void update(Observable obs, Object arg){
   ObsState State = (ObsState)arg;
   int nState = State.Get();

   /* To Handle message for termination. Message ID based on
      assumption that there will not be 9999 ID for Philosopher.*/
   if(nState == 9999) {
      bEndCondition = false;
      return;
   }/* End if.*/

   /* Handle Philosopher with ID same as sent by observable.*/
   if(nState == nID){
    bModified = true;
    return;
   }/* End if.*/
  }/* End of update.*/

  /* This is "heart" of this code. It runs the loop till the bEndCondition
     returns false. The break from this loop is grace full death of the
     thread.*/
  public void run(){
    while (bEndCondition) {
      if(bModified == true){
        DPhil.Eat();                  /* Simulate Picking, Eating.*/
        bModified = false;
      }
    }/* End of While.*/
  }/* End of run.*/
}/* End of PhilosopherObs.*/

