-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundedBufferWithSemaphore.java
More file actions
136 lines (110 loc) · 2.65 KB
/
BoundedBufferWithSemaphore.java
File metadata and controls
136 lines (110 loc) · 2.65 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package interview.boundedbuffer;
import java.util.concurrent.Semaphore;
public class BoundedBufferWithSemaphore {
public static void main(String[] args) throws Exception{
final BlockingQueueWithSemaphore<Integer> q = new BlockingQueueWithSemaphore<>(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=50;i<100;i++){
q.enqueue(new Integer(i));
System.out.println("Enqueued "+i);
}
}catch (InterruptedException ie){
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
try{
for(int i=0;i<50;i++){
int item = q.dequeue();
System.out.println("Dequed "+item);
}
}catch (InterruptedException ie){
}
}
});
Thread t4 = new Thread(new Runnable() {
@Override
public void run() {
try{
for(int i=0;i<50;i++){
int item = q.dequeue();
System.out.println("Dequed "+item);
}
}catch (InterruptedException ie){
}
}
});
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();
//Thread.sleep(1000);
}
}
class BlockingQueueWithSemaphore<T> {
T[] array;
Semaphore semLock = new CountingSemaphore(1,1);
Semaphore semProducer = new CountingSemaphore(1,1);
Semaphore semConsumer = new CountingSemaphore(1,0);
int size = 0;
int capacity;
int head = 0,tail=0;
public BlockingQueueWithSemaphore(int capacity){
array= (T[])new Object[capacity];
this.capacity=capacity;
}
public void enqueue(T item) throws InterruptedException{
semProducer.acquire();
semLock.acquire();
if(tail==capacity){
tail = 0;
}
array[tail] = item;
size++;
tail++;
semLock.release();
semConsumer.release();
}
public T dequeue()throws InterruptedException{
T item = null;
semConsumer.acquire();
semLock.acquire();
if (head == capacity){
head = 0;
}
item = array[head];
array[head] = null;
head++;
size--;
semLock.release();
semProducer.release();
return item;
}
}
class CountingSemaphore extends Semaphore {
public CountingSemaphore(int i, int j){
super(i);
this.release(i-j);
}
}