1.类声明
public class Semaphore implements java.io.Serializable {
}
2.依旧是主要委托Sync内部类实现
// 经典AQS实现版本
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1192457210091910933L;
Sync(int permits) { // 资源初始化
setState(permits);
}
final int getPermits() { // 获得当前资源数
return getState();
}
// 非公平方式获取许可,为什么要写在抽象类中,因为所有的tryAcquire方法都会直接以非公平方式
// 尝试获取许可,无论初始化时使sync是公平还是非公平的。
final int nonfairTryAcquireShared(int acquires) {
for (;;) { // cas减许可
int available = getState();
int remaining = available - acquires;
// 如果剩余的数量小于0(共享模式下判断tryAcquireShared是看返回的整数是否小于0,小于0代表获取失败),代表获取许可失败,AQS中tryAcquire失败将会进队列等待。
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 (;;) {
// 公平模式下将会先判断是否有线程在等待,在等待先排队
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);
}