Semaphore.java 939 Bytes
Newer Older
1 2 3 4
package semaphore;
/*
This class implements a samafor through the use of wait and notify
 */
Luca Arrotta's avatar
Luca Arrotta committed
5 6

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

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

    public synchronized void enter() {
        System.out.println("" + threadsIn + " in the critical region...");
19 20

        // When the maximum number of threads is reached, new threads have to wait
Luca Arrotta's avatar
Luca Arrotta committed
21 22 23 24 25 26 27 28 29 30
        while (threadsIn >= maxNumber) {
            try {this.wait();}
            catch(InterruptedException ie) {ie.printStackTrace();}
        }

        threadsIn++;
    }

    public synchronized void exit() {
        threadsIn--;
31
        // When a thread exits the critical region, it wakes another threads (if there is one) that's waiting to enter the critical region
Luca Arrotta's avatar
Luca Arrotta committed
32 33 34 35
        this.notify();
    }
}