/** * Acquires in shared mode, ignoring interrupts. Implemented by * first invoking at least once {@link #tryAcquireShared}, * returning on success. Otherwise the thread is queued, possibly * repeatedly blocking and unblocking, invoking {@link * #tryAcquireShared} until success. * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquireShared} but is otherwise uninterpreted * and can represent anything you like. */ publicfinalvoidacquireShared(int arg){ //获取共享锁,小于0则放入队列,挂起线程 if (tryAcquireShared(arg) < 0) doAcquireShared(arg); }
/** * Sets head of queue, and checks if successor may be waiting * in shared mode, if so propagating if either propagate > 0 or * PROPAGATE status was set. * * @param node the node * @param propagate the return value from a tryAcquireShared */ privatevoidsetHeadAndPropagate(Node node, int propagate){ //记录当前头结点 Node h = head; // Record old head for check below //把当前获取到锁的节点设置为头结点 setHead(node); //propagate大于0表示后面的节点也需要唤醒 // h.waitStatus < 0 表示节点是可唤醒状态 if (propagate > 0 || h == null || h.waitStatus < 0 || (h = head) == null || h.waitStatus < 0) { Node s = node.next; //后继节点为空或者是共享模式则唤醒 if (s == null || s.isShared()) doReleaseShared(); } }
/** * Release action for shared mode -- signals successor and ensures * propagation. (Note: For exclusive mode, release just amounts * to calling unparkSuccessor of head if it needs signal.) */ privatevoiddoReleaseShared(){ for (;;) { //从头节点开始 Node h = head; if (h != null && h != tail) { int ws = h.waitStatus; //是需要被唤醒的状态 if (ws == Node.SIGNAL) { //CAS方式做并发控制,设置状态为0 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; //唤醒这个节点 unparkSuccessor(h); } //不需要唤醒,则CAS设置状态为PROPAGATE,继续循环 elseif (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; } //头结点没有改变,则设置成功,退出循环 if (h == head) break; } }