Semaphore.java 962 Bytes
Newer Older
1 2
package semaphore;//Class that implements a semaphore, thanks to wait() and notify()
//If you need to recap what a semaphore is, Google is your best friend.
Luca Arrotta's avatar
Luca Arrotta committed
3 4

public class Semaphore {
5 6
    private int maxNumber; //Maximum number of threads
    private int threadsIn; //Number of threads in the critical region
Luca Arrotta's avatar
Luca Arrotta committed
7 8 9 10 11 12 13 14

    Semaphore(int max) {
        maxNumber = max;
        threadsIn = 0;
    }

    public synchronized void enter() {
        System.out.println("" + threadsIn + " in the critical region...");
15
        //When we reach the maximum number of threads, new threads need to wait
Luca Arrotta's avatar
Luca Arrotta committed
16 17 18 19 20 21 22 23 24 25
        while (threadsIn >= maxNumber) {
            try {this.wait();}
            catch(InterruptedException ie) {ie.printStackTrace();}
        }

        threadsIn++;
    }

    public synchronized void exit() {
        threadsIn--;
26
        //Whena thread exits the critical region, it awakens another thread that is waiting (if there is one)
Luca Arrotta's avatar
Luca Arrotta committed
27 28 29 30
        this.notify();
    }
}