Program mutex0

// CS237 - Busy waiting example 0
// ==============================
// When run critical sections will overlap as there
// is no pre or post protocol.

class mutex0 extends Thread
{
  static int N = 2 ;   // Number of processes.
  private int id ;

  public mutex0(int i)
  {
    id = i ;
  }

  private int random(int n)
  {
    return (int) Math.round( n * Math.random() - 0.5 ) ;
  }

  private void busy()
  { 
    try{ sleep(random(500)) ; } catch (InterruptedException e) { }
  }

  private void noncritical()
  {
    System.out.println("Process "+id+" is NON critical") ;
    busy() ;
  }

  private void critical()
  {
    System.out.println("Process "+id+" entering critical section") ;
    busy() ;
    System.out.println("Process "+id+" leaving critical section") ;
  }

  public void run()
  {
    do { noncritical() ; 
         critical() ; } while (true) ;
  }

  public static void main(String [ ] args)
  {
    System.out.println("Busy waiting example 0:") ;
    Thread process[] = new mutex0[N] ;
    for (int i = 0 ; i < N ; i++)
    {  
       process[i] = new mutex0(i) ;
       process[i].start() ;
    }
  }
}