// 首先它继承 AbstractQueuedSynChronizer 这个大家肯定不陌生了 就是AQS
abstract static class Sync extends AbstractQueuedSynChronizer {
private static final long serialVersionUID = 1192457210091910933L;
// 初始化的时候会写入一个状态
Sync(int permits) {
setState(permits);
}
// 获取当前的状态
final int getPermits() {
return getState();
}
// 非公平方式获取信号量
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
// 当前可获取的
int available = getState();
// 计算剩余数量
int remaining = available - acquires;
// 如果剩余数量大于0 就是进行cas修改
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
// 释放信号量
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;
}
}
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;
}
}
}