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