forked from Sheshagiri/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlockingQueue.java
103 lines (98 loc) · 2.17 KB
/
BlockingQueue.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
/**
*
* @author Sheshagiri
*
*/
public class BlockingQueue<E> {
Queue<E> queue;
int elements;
/**
* @param queue
* The underlying "wrapped" queue.
*/
public BlockingQueue(Queue<E> q) {
queue = q;
elements = 2;
}
/**
* Inserts the specified element into the underlying queue, waiting if
* necessary for the underlying queue to be ready to accept new elements.
*
* @param e
* the element to insert.
* @throws InterruptedException
*/
public void push(E e) throws InterruptedException {
while (true) {
synchronized (this) {
while (queue.size() == elements) {
try {
wait();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
System.out.println("Producer produced :: " + e);
elements++;
queue.add(e);
notify();
Thread.sleep(200);
}
}
}
/**
* Retrieves and removes the head of the underlying queue, waiting if
* necessary until it is capable of providing an element.
*
* @return the retrieved element
* @throws InterruptedException
*/
public E pull() throws InterruptedException {
while (true) {
synchronized (this) {
while (queue.size() == 0) {
try {
wait();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
elements--;
System.out.println("Consumer consumed:: " + queue.remove());
notify();
Thread.sleep(200);
}
}
}
public static void main(String[] args) throws InterruptedException {
Queue<String> queue = new LinkedList<String>();
final BlockingQueue<String> blockingQueue = new BlockingQueue<String>(queue);
Thread producer = new Thread(new Runnable() {
@Override
public void run() {
try {
blockingQueue.push(new Date().toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
try {
blockingQueue.pull();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
}
}