public class UseCounter6
{
	Counter c;                         
	public UseCounter6() {
		c = new Counter(0);
	  new Thread() {
      public void run() { callCounter(0); }
	  }.start();
	  new Thread() {
      public void run() { callCounter(1); }
	  }.start();
	}

	private void callCounter(int userID) {
    int val = 0;
    try {
      Thread.sleep(200);
		  val = c.getAndIncrement(userID); 
    } catch (InterruptedException e) {}
		System.out.println("User " + userID + " reporting. Value of counter = " + val);
	}
	
	public static void main(String[] args) {
		new UseCounter6();
	}
}

class Counter {
	private int value;
  private boolean[] flag = new boolean[2];
  private int turn;

	public Counter(int c) {
		value = c;
	}

	public int getAndIncrement(int threadID) {
		int temp = 0;
    int i = threadID;
    int j = 1-i;

    // entry section
    flag[i] = true;
    turn = j;
    while (flag[j] && turn == j) {}

    // critical section
    temp = value;
		value = temp + 1;
		
    // exit section
    flag[i] = false;

		return temp;
	}
}
