1 11 package org.eclipse.ui.internal; 12 13 public class Semaphore { 14 protected long notifications; 15 16 protected Thread operation; 17 18 protected Runnable runnable; 19 20 public Semaphore(Runnable runnable) { 21 this.runnable = runnable; 22 notifications = 0; 23 } 24 25 29 public synchronized boolean acquire(long delay) throws InterruptedException { 30 if (Thread.interrupted()) { 31 throw new InterruptedException (); 32 } 33 long start = System.currentTimeMillis(); 34 long timeLeft = delay; 35 while (true) { 36 if (notifications > 0) { 37 notifications--; 38 return true; 39 } 40 if (timeLeft <= 0) { 41 return false; 42 } 43 wait(timeLeft); 44 timeLeft = start + delay - System.currentTimeMillis(); 45 } 46 } 47 48 public boolean equals(Object obj) { 49 return (runnable == ((Semaphore) obj).runnable); 50 } 51 52 public Thread getOperationThread() { 53 return operation; 54 } 55 56 public Runnable getRunnable() { 57 return runnable; 58 } 59 60 public int hashCode() { 61 return runnable == null ? 0 : runnable.hashCode(); 62 } 63 64 public synchronized void release() { 65 notifications++; 66 notifyAll(); 67 } 68 69 public void setOperationThread(Thread operation) { 70 this.operation = operation; 71 } 72 73 public String toString() { 75 return "Semaphore(" + runnable + ")"; } 77 } 78 | Popular Tags |