public class Semaphor {
	private int counter;

	public Semaphor(int initialCounter) {
		counter = initialCounter;
	}

	public void P(int k) {
		synchronized (this) {
			while (counter - k < 0)
				try {
					this.wait();
				} catch (InterruptedException e) {
					System.err.println("P-Operation interrupted!! (ignoring)");
					e.printStackTrace();
				}

			counter -= k;
		}
	}

	public void V(int k) {
		synchronized (this) {
			counter += k;
			this.notify();
		}
	}
	
	public int free() {
		return counter;
	}
}
