public class UseCounter7 implements Runnable 
{
	Counter c;                         
	public UseCounter7() {
		c = new Counter(0);
	  Thread t1 = new Thread(this);
	  Thread t2 = new Thread(this);
	  t1.start();
	  t2.start();
	}

	public void run() {
    int val = 0;
    try {
      Thread.sleep(20);
		  val = c.getAndIncrement(); 
    } catch (InterruptedException ie) {}
		System.out.println("Value of counter = " + val);
	}
	
	public static void main(String[] args) {
		new UseCounter7();
	}
}

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

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

	public int getAndIncrement() {
		int temp = 0;
    int i = ThreadID.get();
    int j = 1-i;

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

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

		return temp;
	}
}

class ThreadID {
	private static volatile int nextID = 0;
	private static class ThreadLocalID extends ThreadLocal<Integer> {
		protected synchronized Integer initialValue() {
			return nextID++;
		}
	}

	private static ThreadLocalID threadID = new ThreadLocalID();
	public static int get() {
		return threadID.get();
	}

	public static void set(int index) {
		threadID.set(index);
	}
}


