Skip to content

Commit fbc29bb

Browse files
author
zhangquanli
committed
程序清单 14-12 使用 Lock 来实现信号量
1 parent d3e869f commit fbc29bb

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package chapter_14.code_12;
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-12 使用 Lock 来实现信号量
12+
*/
13+
@ThreadSafe
14+
public class SemaphoreOnLock {
15+
private final Lock lock = new ReentrantLock();
16+
// 条件谓词:permitsAvailable (permits > 0)
17+
private final Condition permitsAvailable = lock.newCondition();
18+
@GuardedBy("lock")
19+
private int permits;
20+
21+
SemaphoreOnLock(int initialPermits) {
22+
lock.lock();
23+
try {
24+
permits = initialPermits;
25+
} finally {
26+
lock.unlock();
27+
}
28+
}
29+
30+
// 阻塞并直到:permitsAvailable
31+
public void acquire() throws InterruptedException {
32+
lock.lock();
33+
try {
34+
while (permits <= 0) {
35+
permitsAvailable.await();
36+
}
37+
--permits;
38+
} finally {
39+
lock.unlock();
40+
}
41+
}
42+
43+
public void release() {
44+
lock.lock();
45+
try {
46+
++permits;
47+
permitsAvailable.signal();
48+
} finally {
49+
lock.unlock();
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)