/** * Releases in exclusive mode. Implemented by unblocking one or * more threads if {@link #tryRelease} returns true. * This method can be used to implement method {@link Lock#unlock}. * * @param arg the release argument. This value is conveyed to * {@link #tryRelease} but is otherwise uninterpreted and * can represent anything you like. * @return the value returned from {@link #tryRelease} */ publicfinalbooleanrelease(int arg) { //尝试释放锁,由子类实现 if (tryRelease(arg)) { Nodeh= head; //如果头节点不为null,并且waitStatus不是最初初始化时的状态 if (h != null && h.waitStatus != 0) //唤醒下一个节点 unparkSuccessor(h); returntrue; } returnfalse; }
/** * Wakes up node's successor, if one exists. * * @param node the node */ privatevoidunparkSuccessor(Node node) { /* * If status is negative (i.e., possibly needing signal) try * to clear in anticipation of signalling. It is OK if this * fails or if status is changed by waiting thread. */ intws= node.waitStatus; //ws:CANCELLED=1 ,初始化时等于0,但是进入这个方法前确定ws不等于0, // 所以只要ws不为CANCELLED,就将ws置为0 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. */ Nodes= node.next; //后继节点为null或者后继节点ws为CANCELLED if (s == null || s.waitStatus > 0) { s = null; //从后往前迭代,获取到需要唤醒的离头节点最近的节点 for (Nodet= tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } //找到了需要被唤醒的节点 if (s != null) //唤醒节点所标识的线程 LockSupport.unpark(s.thread); }
/** * Convenience method to park and then check if interrupted * * @return {@code true} if interrupted */ privatefinalbooleanparkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrupted(); }