1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package zeus.util;
25
26 import java.util.*;
27
28 public class Queue extends Thread {
29 protected Vector[] data = null;
30 protected String name = null;
31
32 /***
33 Queues are all now named to make multithread debugging that little bit
34 easier...
35 */
36 public Queue () {
37 this(1);
38 this.name = new String ("unnamed: default");
39 this.start();
40 }
41
42 public Queue(String name) {
43 this(1);
44 this.name = name;
45 this.start();
46
47 }
48
49 public Queue(int levels) {
50 super();
51 data = new Vector[levels];
52 for(int i = 0; i < data.length; i++ )
53 data[i] = new Vector(250);
54 }
55
56
57 public final synchronized Enumeration elements() {
58 Vector out = new Vector();
59 for(int i = 0; i < data.length; i++ )
60 for(int j = 0; j < data[i].size(); j++ )
61 out.add(data[i].get(j));
62 return out.elements();
63 }
64
65 public final synchronized boolean remove(Object elem) {
66 for(int i = 0; i < data.length; i++ ) {
67 for(int j = 0; j < data[i].size(); j++ ) {
68 if ( data[i].contains(elem) ) {
69 data[i].remove(elem);
70 return true;
71 }
72 }
73 }
74 return false;
75 }
76
77 public final synchronized boolean remove(Object elem, int level) {
78 for(int j = 0; j < data[level].size(); j++ ) {
79 if ( data[level].contains(elem) ) {
80 data[level].remove(elem);
81 return true;
82 }
83 }
84 return false;
85 }
86
87 public void enqueue(Object elem) {
88 enqueue(elem, 0);
89 }
90
91
92 public final synchronized void enqueue(Object elem, int level) {
93 data[level].add(elem);
94
95 notify();
96 }
97
98 public final synchronized Object dequeue() {
99
100 while( isEmpty() ) {
101 try {
102 wait();
103 }
104 catch(InterruptedException e) {
105 }
106 }
107
108 for(int i = 0; i < data.length; i++ ) {
109 if ( !data[i].isEmpty() ) {
110 Object elem = data[i].get(0);
111 data[i].remove(elem);
112 return elem;
113 }
114 }
115
116 return null;
117 }
118
119 public final Object peek() {
120 while( isEmpty() ) {
121 try {
122 wait();
123 }
124 catch(InterruptedException e) {
125 }
126 }
127 for(int i = 0; i < data.length; i++ ) {
128 if ( !data[i].isEmpty() )
129 return data[i].get(0);
130 }
131 return null;
132 }
133
134 public final boolean isEmpty() {
135 for(int i = 0; i < data.length; i++ )
136 if ( !data[i].isEmpty() )
137 return false;
138 return true;
139 }
140
141 public final synchronized void clear() {
142 for(int i = 0; i < data.length; i++ )
143 data[i].clear();
144 }
145
146
147 /***
148 * not synchronized because used for estimates, and not
149 * critical
150 */
151 public int size () {
152 return data[0].size();
153 }
154
155
156 /***
157 * not synchronized
158 */
159 public int size (int level) {
160 return data[level].size();
161 }
162 }