forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockingQueue.java
More file actions
95 lines (79 loc) · 2.41 KB
/
BlockingQueue.java
File metadata and controls
95 lines (79 loc) · 2.41 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
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class BlockingQueue {
public static void main(String[] args) {
BoundedBlockingQueue blockingQueue = new BoundedBlockingQueue(4);
new Thread(() -> {
while (true) {
try {
blockingQueue.enqueue((int) Math.random() * 10 / 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "put").start();
new Thread(() -> {
try {
while (true) {
System.out.println(blockingQueue.dequeue());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "take").start();
}
}
class BoundedBlockingQueue {
private Integer[] items;
private volatile int putIndex = 0;
private volatile int takeIndex = 0;
private volatile int count = 0;
private final ReentrantLock reentrantLock;
// 等待 dequeue
private Condition notEmpty;
// 可以 enqueue
private Condition notFull;
public BoundedBlockingQueue(int capacity) {
this.items = new Integer[capacity];
this.reentrantLock = new ReentrantLock();
this.notEmpty = this.reentrantLock.newCondition();
this.notFull = this.reentrantLock.newCondition();
}
public void enqueue(int element) throws InterruptedException {
this.reentrantLock.lock();
try{
while (count == items.length) {
notFull.await();
}
items[putIndex] = element;
count ++;
if (++ putIndex == items.length) {
putIndex = 0;
}
notEmpty.signal();
}finally {
this.reentrantLock.unlock();
}
}
public int dequeue() throws InterruptedException {
this.reentrantLock.lock();
try{
while (count == 0) {
notEmpty.await();
}
final int item = items[takeIndex];
items[takeIndex] = null;
if (++ takeIndex == items.length) {
takeIndex = 0;
}
count --;
notFull.signal();
return item;
}finally {
this.reentrantLock.unlock();
}
}
public int size() {
return count;
}
}