Constructor
// 所謂的信號量就是sync的permits,也就是state
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
// 并且信號量分公平和非公平模式
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
tryAcquireShared
FairSync
protected int tryAcquireShared(int acquires) {
for (;;) {
// 基于公平原則看有沒有到自己
if (hasQueuedPredecessors())
return -1;
int available = getState();
// 計算當(dāng)前所剩的信號量
int remaining = available - acquires;
// 如果所剩的信號量不足,那么直接返回還剩多少
// 如果還有多余的信號量诊霹,且成功更新计呈,那么返回最新的信號量
// 否則信號量還有剩余致份,但是更新state失敗瞎暑,那么有必要進(jìn)入自旋模式哀澈,進(jìn)行重試曙求。
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
NonfairSync
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
// 跟公平模式的唯一不同是碍庵,這里不需要看下一個是否是按順序來的,其他都一樣
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
tryReleaseShared
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
// 歸還信號量悟狱,所以state需要加總回來
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
// CAS成功
if (compareAndSetState(current, next))
return true;
}
}