protectedbooleantryReleaseShared(int releases) { // Decrement count; signal when transition to zero for (;;) {//自旋 intc= getState(); if (c == 0)//计数器已经都是0了,当然会释放失败咯 returnfalse; intnextc= c-1;//释放后,计数器减一 if (compareAndSetState(c, nextc))//CAS修改计数器 return nextc == 0; } }
privatevoiddoReleaseShared() { /* * 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 (;;) { //自旋 Nodeh= head; if (h != null && h != tail) { intws= h.waitStatus; if (ws == Node.SIGNAL) { if (!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; } }