package semaphore; /* This class implements a samafor through the use of wait and notify */ public class Semaphore { //Maximum number of threads private int maxNumber; //Number of threads in the critical region private int threadsIn; Semaphore(int max) { maxNumber = max; threadsIn = 0; } public synchronized void enter() { System.out.println("" + threadsIn + " in the critical region..."); // When the maximum number of threads is reached, new threads have to wait while (threadsIn >= maxNumber) { try {this.wait();} catch(InterruptedException ie) {ie.printStackTrace();} } threadsIn++; } public synchronized void exit() { threadsIn--; // When a thread exits the critical region, it wakes another threads (if there is one) that's waiting to enter the critical region this.notify(); } }