public void unlock() { sync.release(1); } //AbstractQueuedSynchronizer public final boolean release(int arg) { if (tryRelease(arg)) { //如果解锁成功了 Node h = head; //如果头节点不为空 并且状态不是0 //是0 代表没有挂起的线程啊 if (h != null && h.waitStatus != 0) //唤醒线程 unparkSuccessor(h); return true; } return false; } private void unparkSuccessor(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. */ 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); }tryRelease
这个方法也是给子类自己实现的
//Sync 这里实现了他 protected final boolean tryRelease(int releases) { int c = getState() - releases; //想解锁 必须是提前上了锁 否则就是瞎解锁 if (Thread.currentThread() != getExclusiveOwnerThread()) throw new IllegalMonitorStateException(); boolean free = false; //一直解锁到0为止 因为可以加锁无数遍 if (c == 0) { free = true; //解锁成功就设置独有线程为空 setExclusiveOwnerThread(null); } //设置一个值 返回未完全解锁 setState(c); return free; }