01: /*
02: * @(#)Queue.java 1.2 04/12/06
03: *
04: * Copyright (c) 2002,2003 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.multithread;
10:
11: /**
12: * A simple queue implementation
13: */
14: public class Queue {
15:
16: private Cell head;
17: private Cell tail;
18:
19: static class Cell {
20: Object value;
21: Cell next;
22:
23: Cell(Object value) {
24: this .value = value;
25: }
26: }
27:
28: public void enqueue(Object value) {
29: Cell c = new Cell(value);
30: synchronized (this ) {
31: if (head == null) {
32: head = c;
33: tail = c;
34: notify();
35: } else {
36: tail.next = c;
37: tail = c;
38: }
39: }
40: }
41:
42: public boolean isEmpty() {
43: return head == null;
44: }
45:
46: public synchronized Object dequeue() throws InterruptedException {
47: return dequeue(-1);
48: }
49:
50: public synchronized Object dequeue(long timeout)
51: throws InterruptedException {
52: Object ret = null;
53:
54: if (timeout > 0) {
55: if (head == null) {
56: wait(timeout);
57: }
58: } else if (timeout < 0) {
59: while (head == null) {
60: wait();
61: }
62: }
63: if (head != null) {
64: ret = head.value;
65: this.head = head.next;
66: }
67: return ret;
68: }
69: }
|