Skip to content

Commit d3e869f

Browse files
author
zhangquanli
committed
程序清单 14-11 使用显式条件变量的有界缓存
1 parent d1148c4 commit d3e869f

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package chapter_14.code_11;
2+
3+
import net.jcip.annotations.GuardedBy;
4+
import net.jcip.annotations.ThreadSafe;
5+
6+
import java.util.concurrent.locks.Condition;
7+
import java.util.concurrent.locks.Lock;
8+
import java.util.concurrent.locks.ReentrantLock;
9+
10+
/**
11+
* 程序清单 14-11 使用显式条件变量的有界缓存
12+
*/
13+
@ThreadSafe
14+
public class ConditionBoundedBuffer<T> {
15+
protected final Lock lock = new ReentrantLock();
16+
// 条件谓词:notFull (count < items.length)
17+
private final Condition notFull = lock.newCondition();
18+
// 条件谓词:notEmpty (count > 0)
19+
private final Condition notEmpty = lock.newCondition();
20+
private static final int BUFFER_SIZE = 100;
21+
@GuardedBy("lock")
22+
private final T[] items = (T[]) new Object[BUFFER_SIZE];
23+
@GuardedBy("lock")
24+
private int tail, head, count;
25+
26+
// 阻塞并直到:notFull
27+
public void put(T x) throws InterruptedException {
28+
lock.lock();
29+
try {
30+
while (count == items.length) {
31+
notFull.await();
32+
}
33+
items[tail] = x;
34+
if (++tail == items.length) {
35+
tail = 0;
36+
}
37+
++count;
38+
notEmpty.signal();
39+
} finally {
40+
lock.unlock();
41+
}
42+
}
43+
44+
// 阻塞并直到:notEmpty
45+
public T take() throws InterruptedException {
46+
lock.lock();
47+
try {
48+
while (count == 0) {
49+
notEmpty.await();
50+
}
51+
T x = items[head];
52+
items[head] = null;
53+
if (++head == items.length) {
54+
head = 0;
55+
}
56+
--count;
57+
notFull.signal();
58+
return x;
59+
} finally {
60+
lock.unlock();
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)