Program mutex5

// CS237 - Busy waiting example 5
// ==============================
// Fifth attempt at solving the MEP
// using Dekker's algorithm.
// This has arbitration to resolve contention.

class mutex5 extends Thread
{
  static int N = 2 ;   // Number of processes.
  static int insist = 0 ;
  static boolean flag [] = new boolean[N] ; 

  private int id ;

  public mutex5(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") ;
  }

  private boolean wait(int i)
  {
    boolean r = false ;

    for (int j = 0 ; j < N ; j++) if (j != i) r = r | flag[j] ;

    return r ; 
  }

  private void preprotocol()
  {
    do { if (insist != id) flag[id] = false ;
                           do { } while (insist != id) ;
                           flag[id] = true ; }
    while (wait(id)) ;
  }

  private void postprotocol()
  {
    flag[id] = false ;
    insist = random(N) ;
  }

  public void run()
  {
    for (int i = 0 ; i < N ; i++) flag[i] = false ;

    do { noncritical() ; 
         preprotocol() ;
         critical() ; 
         postprotocol() ; } while (true) ;
  }

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