约 300 字 预计阅读 1 分钟
1. 使用 Lock 来实现 Semaphore
代码:
Semaphore
的功能就是允许同时有几个线程操作acquire
方法,permit
会减一,如果为 0,则线程需要等待release
方法,permit
会加一,唤醒等待的线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| public class SemaphoreOnLock {
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private int permit;
public SemaphoreOnLock(int permit) {
this.permit = permit;
}
/**
* 获取锁
*/
public void acquire() {
lock.lock();
try {
while (permit <= 0) {
condition.await();
}
permit--;
} catch (InterruptedException ignored) {
} finally {
lock.unlock();
}
}
public void release() {
lock.lock();
try {
permit++;
condition.signal();
} finally {
lock.unlock();
}
}
}
|
2. 代码实现位置
github 地址