public class CountingSemaphoreTest {
	static int a = 100;
	static int b = 200;

	public static void main(String args[]) {
		final CountingSemaphore cs = new CountingSemaphore(1);
		Thread t1, t2;

		/* T1 tries to transfer from b into a */
		t1 = new Thread(new Runnable() {
			public void run() {
				try {
					for (int i = 0; i < 100000; i++) {
						cs.P();
						a += 50;
						b -= 50;
						cs.V();
					}
				} catch (InterruptedException ie) {
					System.out.println("URK!");
				}
			}
		});

		/* T2 tries to tranfer from a into b */
		t2 = new Thread(new Runnable() {
			public void run() {
				try {
					for (int i = 0; i < 100000; i++) {
						cs.P();
						a -= 50;
						b += 50;
						cs.V();
					}
				} catch (InterruptedException ie) {
					System.out.println("URK!");
				}
			}
		});

		System.out.println("before: a+b=" + (a + b));

		t1.start();
		t2.start();

		try {
			t1.join();
			t2.join();
		} catch (InterruptedException ie) {
			System.out.println("Interrupted during join");
		}

		System.out.println("after:  a+b=" + (a + b));
	}
}
