// Michael Tartaglia
// 27 November 2002
// Dining Philosophers

// WAITER: checks philosopher's hunger values and serves
//         food to the current philosopher


public class Waiter extends Thread{
   private int helpingsToServe;	// amount of desired resource
   private Thread runner;
   private Philosopher[] p;
   private int who,		// current index
	       maxWho;		// total number to serve

   public Waiter(Philosopher[] phils, int n) {
      who = 0;
      maxWho = n;
      p = phils;
   }

   public void start() {
      runner = new Thread(this);
      runner.start();
   }

   public synchronized void run() {
      while (true) {
         askAndServe(p[who]);
         who = (who+1) % maxWho;
      }
   }
	
   public synchronized void askAndServe(Philosopher p) {
      if (!p.isEating() && p.wasServed()) {
         System.out.println("\nWaiter sees that Philosopher #"
			 + p.name() + " did not yet eat last serving.");
      } else if (p.isEating()) {
         System.out.println("\nWaiter sees that Philosopher #"
			 + p.name() + " is still eating.");
      } else if (p.isHungry()) {
         System.out.println("\nWaiter asking philosopher #" + p.name()
		 	 + " if he is hungry.");
	 helpingsToServe = p.howHungry();
	 System.out.println("Waiter serving requested "
			 + helpingsToServe + " helpings to Philosopher #"
			 + p.name() + ".");
	 p.served(helpingsToServe);
         try {runner.sleep(1000);}
         catch (InterruptedException ie) {}
      } else {
	 System.out.println("\nWaiter notes Philosopher #" + p.name()
			 + " is thinking right now.");
      }
   }

}
