privatestaticbooleanshouldParkAfterFailedAcquire(Node pred, Node node){ int ws = pred.waitStatus; if (ws == Node.SIGNAL) /* * This node has already set status asking a release * to signal it, so it can safely park */ //前继节点已经设置好unpark了,所以后继可以安全的park returntrue; if (ws > 0) { /* * Predecessor was cancelled. Skip over predecessors and * indicate retry. */ //跳过被取消的节点 do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { //0或者PROPAGATE(CONDITION状态用在ConditionObject,这里不会是CONDITION这个值) //waitStatus=0(初始化)或PROPAGATE,会先重试确定无法acquire到再park /* * waitStatus must be 0 or PROPAGATE. Indicate that we * need a signal, but don't park yet. Caller will need to * retry to make sure it cannot acquire before parking. */ //更新前继节点状态为SIGNAL compareAndSetWaitStatus(pred, ws, Node.SIGNAL); } returnfalse; } privatefinalbooleanparkAndCheckInterrupt(){ //park并且设置线程的interrupted LockSupport.park(this); return Thread.interrupted(); }
publicfinalbooleanrelease(int arg){ //tryRelease由子类实现,通过设置state值来达到同步的效果 if (tryRelease(arg)) { Node h = head; //waitStatus=0说明是初始化的空队列 if (h != null && h.waitStatus != 0) //唤醒后继节点 unparkSuccessor(h); returntrue; } returnfalse; } privatevoidunparkSuccessor(Node node){ /* * If status is negative (i.e., possibly needing signal) try clear in anticipation of signalling. It is OK if this * fails or if status is changed by waiting thread. int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0); /* * Thread to unpark is held in successor, which is normally * just the next node. But if cancelled or apparently null, * traverse backwards from tail to find the actual * non-cancelled successor. */ Node s = node.next; if (s == null || s.waitStatus > 0) { s = null; for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread);
publicfinalvoidacquireShared(int arg){ //如果没有许可则入队等待 if (tryAcquireShared(arg) < 0) doAcquireShared(arg); } privatevoiddoAcquireShared(int arg){ //添加到队列 final Node node = addWaiter(Node.SHARED); try { boolean interrupted = false; //等待前继释放并传播 for (;;) { final Node p = node.predecessor(); if (p == head) { //尝试获取许可 int r = tryAcquireShared(arg); if (r >= 0) { //获取成功则前继出队,跟独占不同的是会继续向后继节点传播唤醒操作, //保证剩下的线程能尽快地获取剩下的许可。 setHeadAndPropagate(node, r); p.next = null; // help GC if (interrupted) selfInterrupt(); return; } } //p不是头节点且获取不到许可 if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } catch (RuntimeException ex) { cancelAcquire(node); throw ex; } } privatevoidsetHeadAndPropagate(Node node, int propagate){ Node h = head; // Record old head for check below setHead(node); /* * Try to signal next queued node if: * Propagation was indicated by caller, * or was recorded (as h.waitStatus) by a previous operation * (note: this uses sign-check of waitStatus because * PROPAGATE status may transition to SIGNAL.) * and * The next node is waiting in shared mode, * or we don't know, because it appears null * * The conservatism in both of these checks may cause * unnecessary wake-ups, but only when there are multiple * racing acquires/releases, so most need signals now or soon * anyway. */ /** * 尝试唤醒后继节点,propagate>0说明许可还有能继续被线程acquires * 或者之前的head被设置为PROPAGATE(PROPAGATE或以转换为SIGNAL) * 或者为null。检查有些保守,在多竞争时,可能出现不必要的唤醒 */ if (propagate > 0 || h == null || h.waitStatus < 0) { Node s = node.next; if (s == null || s.isShared()) //唤醒后继节点 doReleaseShared(); } }
publicfinalbooleanreleaseShared(int arg){ if (tryReleaseShared(arg)) { doReleaseShared(); returntrue; } returnfalse; } 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 (;;) { Node h = head; //队列不为空且有后继节点 if (h != null && h != tail) { int ws = h.waitStatus; //不管共享还是独占模式,只要节点waitStatus为SIGNAL状态都唤醒 if (ws == Node.SIGNAL) { //将waitStatus设置为0 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 } //如果循环过程中head节点被修改了则重试 if (h == head) // loop if head changed break; } }