forked from xiaoningning/java-algorithm-2010
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockingQueue.java
More file actions
56 lines (41 loc) · 1.16 KB
/
BlockingQueue.java
File metadata and controls
56 lines (41 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.LinkedList;
import java.util.Queue;
public class BlockingQueue<T> {
private int maxSize;
private Queue<T> queue;
public BlockingQueue(int size) {
maxSize = size;
queue = new LinkedList<T>();
}
public synchronized T dequeue() {
while (queue.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T value = queue.poll();
notifyAll();
return value;
}
public synchronized void enqueue(T value) {
while (queue.size() == maxSize) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(value);
notifyAll();
}
public static void main(String[] args) throws Exception{
BlockingQueue<String> queue = new BlockingQueue<String>(2);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(400);
}
}