Skip to content

Commit 8e9f55d

Browse files
author
zhangquanli
committed
程序清单 14-4 调用 GrumpyBoundedBuffer 的代码
1 parent 4e7119c commit 8e9f55d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package chapter_14.code_04;
2+
3+
import chapter_14.code_02.BaseBoundedBuffer;
4+
import net.jcip.annotations.ThreadSafe;
5+
6+
/**
7+
* 程序清单 14-4 调用 GrumpyBoundedBuffer 的代码
8+
*/
9+
@ThreadSafe
10+
public class GrumpyBoundedBuffer<V> extends BaseBoundedBuffer<V> {
11+
public GrumpyBoundedBuffer() {
12+
this(100);
13+
}
14+
15+
public GrumpyBoundedBuffer(int size) {
16+
super(size);
17+
}
18+
19+
public synchronized void put(V v) throws BufferFullException {
20+
if (isFull()) {
21+
throw new BufferFullException();
22+
}
23+
doPut(v);
24+
}
25+
26+
public synchronized V take() throws BufferEmptyException {
27+
if (isEmpty()) {
28+
throw new BufferEmptyException();
29+
}
30+
return doTake();
31+
}
32+
}
33+
34+
class ExampleUsage {
35+
private GrumpyBoundedBuffer<String> buffer;
36+
int sleepGranularity = 50;
37+
38+
void useBuffer() throws InterruptedException {
39+
while (true) {
40+
try {
41+
String item = buffer.take();
42+
// 对于 item 执行一些操作
43+
break;
44+
} catch (BufferEmptyException e) {
45+
Thread.sleep(sleepGranularity);
46+
}
47+
}
48+
}
49+
}
50+
51+
class BufferFullException extends RuntimeException {
52+
}
53+
54+
class BufferEmptyException extends RuntimeException {
55+
}

0 commit comments

Comments
 (0)