home *** CD-ROM | disk | FTP | other *** search
/ The Net: Ultimate Internet Guide / WWLCD1.ISO / pc / java / unuy2wen / cybcerone / utils / semaphore.java < prev    next >
Encoding:
Java Source  |  1996-08-14  |  1.0 KB  |  50 lines

  1. // Semaphore.java
  2. // 10.02.96
  3. //
  4. // implements a semaphore for synchronization
  5.  
  6. package cybcerone.utils;
  7.  
  8. /**
  9.  * Your basic semaphore, used for synchronization.
  10.  * Only one object can hold the semaphore at any given point in time.
  11.  */
  12. public class Semaphore {
  13.   private boolean occupied;
  14.   private Object owner;
  15.  
  16.   public Semaphore () {
  17.     occupied = false;
  18.     owner = null;
  19.   }
  20.   
  21.   /** 
  22.    * Request the semaphore, if it's not free wait until it is.
  23.    *
  24.    * @param requester The object requesting the semaphore
  25.    */
  26.   public synchronized void p (Object requester) {
  27.     while (occupied) {
  28.       try {
  29.     wait ();
  30.       } catch (InterruptedException e) {
  31.       }
  32.     }
  33.     occupied = true;
  34.     owner = requester;
  35.   }
  36.  
  37.   /**
  38.    * Release the semaphore.  No effect if releaser isn't the current owner.
  39.    *
  40.    * @param releaser The object releasing the semaphore.
  41.    */
  42.   public synchronized void v (Object releaser) {
  43.     if (releaser == owner) {
  44.       occupied = false;
  45.       owner = null;
  46.       notifyAll ();
  47.     }
  48.   }
  49. }
  50.