-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockingQueue.java
More file actions
39 lines (32 loc) · 939 Bytes
/
Copy pathBlockingQueue.java
File metadata and controls
39 lines (32 loc) · 939 Bytes
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
package producerconsumer;
import java.util.LinkedList;
import java.util.Queue;
public class BlockingQueue<T> {
private int compacity;
private final Queue<T> items = new LinkedList<>();
public BlockingQueue(int compacity) {
this.compacity = compacity;
}
public synchronized void put(T value) throws InterruptedException {
while (items.size() == compacity) {
System.out.println("Queue is full");
wait();
}
items.add(value);
notifyAll();
}
public synchronized T take() throws InterruptedException {
while (items.size() == 0) {
System.out.println("Queue is empty");
wait();
}
notifyAll();
return items.poll();
}
public synchronized int size() {
return items.size();
}
public int getCompacity() {
return compacity;
}
}