-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundedBuffer.java
More file actions
106 lines (89 loc) · 1.99 KB
/
BoundedBuffer.java
File metadata and controls
106 lines (89 loc) · 1.99 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
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
104
105
106
package interview.boundedbuffer;
public class BoundedBuffer {
public static void main(String[] args) throws Exception{
final BlockingQueue<Integer> q = new BlockingQueue<>(5);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try{
for(int i=0;i<50;i++){
q.enqueue(new Integer(i));
System.out.println("Enqueued "+i);
}
}catch (InterruptedException ie){
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try{
for(int i=0;i<25;i++){
int num = q.dequeue();
System.out.println("Dequeued "+num);
}
}catch (InterruptedException ie){
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
try{
for(int i=0;i<25;i++){
int num = q.dequeue();
System.out.println("Dequeued "+num);
}
}catch (InterruptedException ie){
}
}
});
t1.start();
Thread.sleep(4000);
t2.start();
t2.join();
t3.start();
t3.join();
}
}
class BlockingQueue<T> {
T[] array;
Object lock = new Object();
int size = 0;
int capacity;
int head = 0,tail=0;
public BlockingQueue(int capacity){
array= (T[])new Object[capacity];
this.capacity=capacity;
}
public void enqueue(T item) throws InterruptedException{
synchronized (lock){
while (size == capacity){
lock.wait();
}
if(tail==capacity){
tail = 0;
}
array[tail] = item;
size++;
tail++;lock.notifyAll();
}
}
public T dequeue()throws InterruptedException{
T item = null;
synchronized (lock){
while (size==0){
lock.wait();
}
if (head == capacity){
head = 0;
}
item = array[head];
array[head] = null;
head++;
size--;
lock.notifyAll();
}
return item;
}
}