public class Semaphore implements java.io.Serializable {
}
2.依舊是主要委托Sync內(nèi)部類實(shí)現(xiàn)
Sync抽象類
// 經(jīng)典AQS實(shí)現(xiàn)版本
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1192457210091910933L;
Sync(int permits) { // 資源初始化
setState(permits);
}
final int getPermits() { // 獲得當(dāng)前資源數(shù)
return getState();
}
// 非公平方式獲取許可熔吗,為什么要寫在抽象類中靡菇,因?yàn)樗械膖ryAcquire方法都會(huì)直接以非公平方式
// 嘗試獲取許可凿滤,無(wú)論初始化時(shí)使sync是公平還是非公平的。
final int nonfairTryAcquireShared(int acquires) {
for (;;) { // cas減許可
int available = getState();
int remaining = available - acquires;
// 如果剩余的數(shù)量小于0(共享模式下判斷tryAcquireShared是看返回的整數(shù)是否小于0利诺,小于0代表獲取失敗),代表獲取許可失敗剩燥,AQS中tryAcquire失敗將會(huì)進(jìn)隊(duì)列等待慢逾。
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
// cas釋放許可,公平和非公平模式都一樣
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)) // 沒有條件判斷灭红,只要許可被加上去就返回true
return true;
}
}
// 純粹的cas減掉一部分許可
final void reducePermits(int reductions) {
for (;;) {
int current = getState();
int next = current - reductions;
if (next > current) // underflow
throw new Error("Permit count underflow");
if (compareAndSetState(current, next))
return;
}
}
// 許可歸零
final int drainPermits() {
for (;;) {
int current = getState();
if (current == 0 || compareAndSetState(current, 0))
return current;
}
}
}
非公平模式
static final class NonfairSync extends Sync {
private static final long serialVersionUID = -2694183684443567898L;
NonfairSync(int permits) {
super(permits);
}
protected int tryAcquireShared(int acquires) {
// 直接使用抽象類中的方法
return nonfairTryAcquireShared(acquires);
}
}
公平模式
static final class FairSync extends Sync {
private static final long serialVersionUID = 2014338818796000944L;
FairSync(int permits) {
super(permits);
}
protected int tryAcquireShared(int acquires) {
for (;;) {
// 公平模式下將會(huì)先判斷是否有線程在等待侣滩,在等待先排隊(duì)
if (hasQueuedPredecessors())
return -1;
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
}
3.具體的獲取許可方法
// 獲取許可直接委托sync
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}