// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
public class Semaphore {
    private boolean inuse;
    private int counter;

    public Semaphore() {
        inuse = false;
        counter = 0;
    }

    public synchronized void get() {
        counter++;
        while (inuse) {
            try {
                wait();
            } catch (InterruptedException e) {
                // ignore
            }
        }
        inuse = true;
        counter--;
    }
    
    public synchronized void release() {
        inuse = false;
        notify();
    }
    public synchronized boolean available() {
        return inuse;
    }
    public synchronized int waiting() {
        return counter;
    }
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Semaphore sem = new Semaphore();
        MyThread[] t = new MyThread[10];
        for(int i = 0; i < t.length; i++) {
            t[i] = new MyThread(sem);        
        }
        for(int i = 0; i < t.length; i++) {
            t[i].start();      
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            // ignore
        }
        System.out.println("Waiting=" + sem.waiting());
        for(int i = 0; i < t.length; i++) {
            try {
                t[i].join();        
            } catch (InterruptedException e) {
                // ignore
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("Time=" + (end - start));
    }
    
}
class MyThread extends Thread {
    private Semaphore sem;
    public MyThread(Semaphore sem) {
        this.sem = sem;
    }
    public void run() {
        sem.get();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // ignore
        }
        sem.release();
    }
}
