/* * Semaphore.java * From: Silberschatz, Galvin, Gagne: AOS, FIgure 7.41 * * */ public class Semaphore { private int value; // Object creation public Semaphore() { value = 0; }; // Object creation with initial value public Semaphore(int v) { value = v; }; // Wait on the semaphore public synchronized void P() { while(value <= 0) { try { wait(); } catch(InterruptedException e){} }; value--; }; // Wait on the semaphore (alternative method) public synchronized void Wait() { P(); }; // Release the semaphore public synchronized void V() { //System.out.println("V()\n"); ++value; notify(); }; // Release the semaphore (alternative method) public synchronized void Signal() { V(); }; };