Skip to content

Commit 2153bbc

Browse files
author
zhangquanli
committed
程序清单 14-6 使用条件队列实现的有界缓存
1 parent fb4998c commit 2153bbc

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package chapter_14.code_06;
2+
3+
import chapter_14.code_02.BaseBoundedBuffer;
4+
import net.jcip.annotations.ThreadSafe;
5+
6+
/**
7+
* 程序清单 14-6 使用条件队列实现的有界缓存
8+
*/
9+
@ThreadSafe
10+
public class BoundedBuffer<V> extends BaseBoundedBuffer<V> {
11+
// 条件谓词:not-full(!isFull())
12+
// 条件谓词:not-empty(!isEmpty())
13+
14+
public BoundedBuffer() {
15+
this(100);
16+
}
17+
18+
public BoundedBuffer(int size) {
19+
super(size);
20+
}
21+
22+
// 阻塞并直到:not-full
23+
public synchronized void put(V v) throws InterruptedException {
24+
while (isFull()) {
25+
wait();
26+
}
27+
doPut(v);
28+
notifyAll();
29+
}
30+
31+
// 阻塞并直到:not-empty
32+
public synchronized V take() throws InterruptedException {
33+
while (isEmpty()) {
34+
wait();
35+
}
36+
V v = doTake();
37+
notifyAll();
38+
return v;
39+
}
40+
}

0 commit comments

Comments
 (0)