import java.lang.Math;

public class Peterson extends Thread {

  static enum Estado {QUIERE_ENTRAR,RESTO_PROCESO};
  static int I = 0;
  static final int NUM_ITER = 20000;
  static volatile int turno = 0;
  static Estado C[] = {Estado.RESTO_PROCESO,Estado.RESTO_PROCESO};
  int i;  // identificador del hilo
  int j; // identificador del otro hilo

  public void run() {
    //try{
    for (int l = 0; l < NUM_ITER; l++) {
      // Protocolo de entrada
      C[i] = Estado.QUIERE_ENTRAR;
      turno = j;
      while( (C[j] == Estado.QUIERE_ENTRAR) && (turno == j) );

      // Seccion critica
      I = I + 1;
      //sleep((long)(Math.random()));
      //System.out.println("En hilo "+i+", I = "+I);

      // Protocolo de salida
      C[i] = Estado.RESTO_PROCESO;
    }
    //} catch ( InterruptedException e ){return;}
  }

  Peterson(int id){
    this.i = id;
    this.j = (id == 1)? 0 : 1;
  }

  public static void main(String args[]) {
    Thread thr1 = new Peterson(0);
    Thread thr2 = new Peterson(1);
    thr1.start();
    thr2.start();
    try {
      thr1.join();
      thr2.join();
    } catch ( InterruptedException e ){return;}

    System.out.println("I = " + I);
  }
}
