File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
src/main/java/chapter_14/code_02 Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ package chapter_14 .code_02 ;
2
+
3
+ import net .jcip .annotations .GuardedBy ;
4
+ import net .jcip .annotations .ThreadSafe ;
5
+
6
+ /**
7
+ * 程序清单 14-2 有界缓存实现的基类
8
+ */
9
+ @ ThreadSafe
10
+ public class BaseBoundedBuffer <V > {
11
+ @ GuardedBy ("this" )
12
+ private final V [] buf ;
13
+ @ GuardedBy ("this" )
14
+ private int tail ;
15
+ @ GuardedBy ("this" )
16
+ private int head ;
17
+ @ GuardedBy ("this" )
18
+ private int count ;
19
+
20
+ protected BaseBoundedBuffer (int capacity ) {
21
+ this .buf = (V []) new Object [capacity ];
22
+ }
23
+
24
+ protected synchronized final void doPut (V v ) {
25
+ buf [tail ] = v ;
26
+ if (++tail == buf .length ) {
27
+ tail = 0 ;
28
+ }
29
+ ++count ;
30
+ }
31
+
32
+ protected synchronized final V doTake () {
33
+ V v = buf [head ];
34
+ buf [head ] = null ;
35
+ if (++head == buf .length ) {
36
+ head = 0 ;
37
+ }
38
+ --count ;
39
+ return v ;
40
+ }
41
+
42
+ public synchronized final boolean isFull () {
43
+ return count == buf .length ;
44
+ }
45
+
46
+ public synchronized final boolean isEmpty () {
47
+ return count == 0 ;
48
+ }
49
+ }
You can’t perform that action at this time.
0 commit comments