import java.util.concurrent.*;

public class UseCounter9 {
	Counter c;                         
	public UseCounter9() {
		c = new Counter(0);
		for (int i = 0; i < 10; i++) {
      final int userID = i;
		  new Thread() {
		    public void run() { callCounter(userID); }
		  }.start();
		}
	}

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

class Counter {
	private int value;
	Semaphore sem = new Semaphore(1, true);

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

	public int getAndIncrement() {
		int temp = 0;
    try {
  		sem.acquire();
  		temp = value;
  		value = temp + 1;  
    } catch (InterruptedException ie) {}
      finally {
    		sem.release();
      }

		return temp;
	}
}
