File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
src/main/java/chapter_14/code_04 Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments