源码

  1. public void unlock() {
  2. sync.release(1);
  3. }
  1. public final boolean release(int arg) {
  2. if (tryRelease(arg)) {
  3. Node h = head;
  4. //waitStatus =-1 表示自己有义务去唤醒别人
  5. if (h != null && h.waitStatus != 0)
  6. unparkSuccessor(h);
  7. return true;
  8. }
  9. return false;
  10. }
  1. protected final boolean tryRelease(int releases) {
  2. int c = getState() - releases;
  3. if (Thread.currentThread() != getExclusiveOwnerThread())
  4. //基本不会发生
  5. throw new IllegalMonitorStateException();
  6. boolean free = false;
  7. if (c == 0) {
  8. free = true;
  9. setExclusiveOwnerThread(null);
  10. }
  11. setState(c);
  12. return free;
  13. }

unparkSuccessor

  1. private void unparkSuccessor(Node node) {
  2. int ws = node.waitStatus;
  3. if (ws < 0)
  4. //将waitstatus由-1改成0,防止多线程情况下的访问导致需要额外唤醒别的线程
  5. com
  6. Node s = node.next;
  7. //非正常情况 下一个节点被中断
  8. if (s == null || s.waitStatus > 0) {
  9. s = null;
  10. for (Node t = tail; t != null && t != node; t = t.prev)
  11. if (t.waitStatus <= 0)
  12. s = t;
  13. }
  14. //正常情况
  15. if (s != null)
  16. LockSupport.unpark(s.thread);
  17. }

解锁流程图

解锁之前

image.png

解锁之后

image.png