protectedfinalbooleantryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases; //释放资源则可用数增加 releasesif (next < current) // overflowthrownew Error("Maximum permit count exceeded");
if (compareAndSetState(current, next)) //cas操作释放资源returntrue;
}
}
AQS#doReleaseShared
privatevoid doReleaseShared() {
/*
* Ensure that a release propagates, even if there are other
* in-progress acquires/releases. This proceeds in the usual
* way of trying to unparkSuccessor of head if it needs
* signal. But if it does not, status is set to PROPAGATE to
* ensure that upon release, propagation continues.
* Additionally, we must loop in case a new node is added
* while we are doing this. Also, unlike other uses of
* unparkSuccessor, we need to know if CAS to reset status
* fails, if so rechecking.
*/
for (;;) {
Node h = head;
//最终状态 signal = 》0 = 》 PROPAGATE 经过一步0的操作时因为unparkSuccessor 中会有cas设置为0状态if (h != null && h != tail) {
int ws = h.waitStatus; //获取头节点的状态if (ws == Node.SIGNAL) { //如果节点的状态为唤醒,则置为0if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) //失败则跳出循环重新开始
continue; // loop to recheck cases
unparkSuccessor(h); //唤醒下一个节点
} elseif (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) //将节点设置为可传播
continue; // loop on failed CAS
}
//如果头节点被更换,即下一个节点被唤醒if (h == head) // loop if head changed
break;
}
}