Semaphore
Semaphore是信号量 ,当线程acquire()获取一个信号量(permit)时才可以不阻塞,每个release方法归还一个信号量。
- 构造函数
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
- 尝试获取许可证
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//模板方法模式
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
//这个也是AQS的方法,模板方法模式
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
//许可证可能是负的
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//Semaphore的获取锁方法
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
//尝试获取锁,如果没有许可证了返回的是负数
//如果获取许可证成功,返回剩余许可证(大于0)
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
- 释放许可证
//AQS的方法
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
//唤醒同步队列的首个线程节点
doReleaseShared();
return true;
}
return false;
}
//semaphore的方法,尝试释放锁(释放许可证),CAS成功返回ture
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}