Universidad de Costa Rica

Escuela de Ciencias de la Computación e Informática

CI-0122 Sistemas operativos

Ejemplos

CI0122 / Ejemplos / java / DiningPhilosphers


public class diningph {

   public enum State { Thinking, Hungry, Eating }
   private State[] state;		// Each of the philosophers state
   private ConditionJava[] self;	// Access control to chopstick
   private MutexJava mutex;

   public diningph() {
      state = new State[ 5 ];
      self  = new ConditionJava[ 5 ];
      mutex = new MutexJava();

      for ( int i = 0; i < 5; i++ ) {
         state[ i ] = State.Thinking;
         self[ i ] = new ConditionJava();
      }

   }

   public void pickup( int who ) {

    state[ who ] = State.Hungry;
    int k = who + 1;
    printstr( k, "will try to pickup sticks" );
    print( k );
    test( who );
    if ( state[ who ] == State.Hungry ) {
        printstr( k, "sticks are busy, will wait for them " );
        synchronized ( self[ who ] ) {
           self[ who ].Wait();
        }
    }

    printstr( k, "will start eating" );

   }

   public synchronized void putdown( int who ) {

      int k = who + 1;
      printstr( k, "end eating, will putdown sticks" );
      state[ who ] = State.Thinking;
      test( (who + 4) % 5 );
      test( (who + 1) % 5 );

   }

   private void test( int i ) {
      if ( ( state[ (i + 4) % 5 ] != State.Eating ) && 
           ( state[ i ] == State.Hungry ) && 
           ( state[ (i + 1) % 5] != State.Eating ) ) {
           state[ i ] = State.Eating;
   int k = i + 1;
   printstr( k, "voy a hacer signal " );
           synchronized ( self[ i ] ) {
              self[ i ].Signal();
           }
       }

   }

   public void print( int who ) {

      mutex.Wait();
      for ( int i = 0; i < 5; i++  ) {
          System.out.printf( "(%d) Philosopher %d is %s \n", who, i + 1, (state[i]==State.Hungry)?"Hungry":(state[i]==State.Thinking)?"Thinking":"Eating");

      }
      mutex.Signal();

   }

   public synchronized void printstr( int who, String s ) {

      mutex.Wait();
      System.out.println( "Philosopher " + who + ", " + s );
      mutex.Signal();

   }

}