01: /*******************************************************************************
02: * Copyright (c) 2000, 2006 IBM Corporation and others.
03: * All rights reserved. This program and the accompanying materials
04: * are made available under the terms of the Eclipse Public License v1.0
05: * which accompanies this distribution, and is available at
06: * http://www.eclipse.org/legal/epl-v10.html
07: *
08: * Contributors:
09: * IBM Corporation - initial API and implementation
10: *******************************************************************************/package org.eclipse.ui.internal;
11:
12: public class Semaphore {
13: protected long notifications;
14:
15: protected Thread operation;
16:
17: protected Runnable runnable;
18:
19: public Semaphore(Runnable runnable) {
20: this .runnable = runnable;
21: notifications = 0;
22: }
23:
24: /**
25: * Attempts to acquire this semaphore. Returns true if it was successfully acquired,
26: * and false otherwise.
27: */
28: public synchronized boolean acquire(long delay)
29: 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: // for debug only
74: public String toString() {
75: return "Semaphore(" + runnable + ")"; //$NON-NLS-1$ //$NON-NLS-2$
76: }
77: }
|