/*
 * A CountingSemaphore supports two operations on an integer count
 * value:
 *
 *    P() decrements the value and blocks the thread if the new
 *        value is less than zero
 *
 *    V() increments the value and then, if it is zero or less,
 *        wakes up one of the threads that has blocked on the 
 *        counting semaphore.
 *
 * Both of these operations are atomic.
 *
 * This class implements them using synchronized methods.  However,
 * semaphores are typically used as a lower-level operation from which
 * facilities like Java's synchronized methods may be implemented.
 */

public class CountingSemaphore {

	int val;

	public CountingSemaphore(int x) {
		val = x;
	}

	public synchronized void P() throws InterruptedException {
		val--;
		if (val < 0)
			wait();
	}

	public synchronized void V() {
		val++;
		if (val <= 0)
			notify();
	}
}
