Universidad de Costa Rica

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

CI-0122 Sistemas Operativos

Temas

CI0122 / Temas revisados / Semana-06 / Java / DP


import java.util.Random;


public class philo extends Thread {

   private static int NUMTHRDS = 5;
   public static Mutex mutex;
   private static DiningPh dp;
   private int who;

   public philo( int i ) {
      who = i;

   }


   public void run(){

      int eats, thinks;
      Random r = new Random();

      for ( int i = 0; i < 10; i++ ) {

         print( "Philo # " + who + ", round " + i + "\n" );

         dp.pickup( who);
         eats = r.nextInt( 5 ) * 1000;
         try {
            sleep( eats );
         } catch ( InterruptedException e ) {
            System.out.println( e );
         }

         dp.putdown( who);
         thinks = r.nextInt( 5 ) * 1000;
         try {
            sleep( thinks );
         } catch ( InterruptedException e ) {
            System.out.println( e );
         }
      }

      System.out.println( "Thread finishing ... " + who );

   }

   private void print( String s ) {
      mutex.Wait();	
      System.out.println( s );
      mutex.Signal();

   }

   public static void main ( String[] args ) {
      dp = new DiningPh();
      mutex = new Mutex();
      for ( int i = 0; i < NUMTHRDS; i++ ) {
          philo p = new philo( i );
          p.start();
      }

   }

}