1 11 package org.eclipse.core.runtime.adaptor; 12 13 16 public class Semaphore { 17 protected long notifications; 18 19 public Semaphore(int count) { 20 notifications = count; 21 } 22 23 26 public synchronized void acquire() { 27 while (true) { 28 if (notifications > 0) { 29 notifications--; 30 return; 31 } 32 try { 33 wait(); 34 } catch (InterruptedException e) { 35 } 37 } 38 } 39 40 44 public synchronized boolean acquire(long delay) { 45 long start = System.currentTimeMillis(); 46 long timeLeft = delay; 47 while (true) { 48 if (notifications > 0) { 49 notifications--; 50 return true; 51 } 52 if (timeLeft < 0) 53 return false; 54 try { 55 wait(timeLeft); 56 } catch (InterruptedException e) { 57 } 59 timeLeft = start + delay - System.currentTimeMillis(); 60 } 61 } 62 63 public synchronized void release() { 64 notifications++; 65 notifyAll(); 66 } 67 68 public String toString() { 70 return "Semaphore(" + notifications + ")"; } 72 } | Popular Tags |