// 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 MultiSemaphore {
   public final static int EXCLUSIVE = 1;
   public final static int SHARED = 2;

   private int nouser;
   private int mode;

   public MultiSemaphore() {
      nouser = 0;
   }

   public synchronized void get(int mode) {
      while ((this.mode == EXCLUSIVE || mode == EXCLUSIVE) && nouser > 0) {
         try {
            wait();
         } catch (InterruptedException e) {
            // ignore
         }
      }
      nouser++;
      this.mode = mode;
   }
    
   public synchronized void release() {
      nouser--;
      notifyAll();
   }

   public static void main(String[] args) {
      long start = System.currentTimeMillis();
      MultiSemaphore sem = new MultiSemaphore();
      MyThread[] t = new MyThread[10];
      for(int i = 0; i < t.length; i++) {
         t[i] = new MyThread(sem, i % 2 == 0);        
      }
      for(int i = 0; i < t.length; i++) {
         t[i].start();      
      }
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e1) {
         // ignore
      }
      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 MultiSemaphore sem;
   private boolean excl;
   public MyThread(MultiSemaphore sem, boolean excl) {
      this.sem = sem;
      this.excl = excl;
   }
   public void run() {
      sem.get(excl ? MultiSemaphore.EXCLUSIVE : MultiSemaphore.SHARED);
      try {
         Thread.sleep(3000);
      } catch (InterruptedException e) {
         // ignore
      }
      sem.release();
   }
}
