zoukankan      html  css  js  c++  java
  • ReentrantLock 锁释放源码分析

    ReentrantLock 锁释放源码分析:

    调用的是unlock 的方法:

    public void unlock() {

            sync.release(1); 

    }

    接下来分析release() 方法:

    public final boolean release(int arg) {   // arg=1

            if (tryRelease(arg)) {         //独占锁是否被释放  当state=0时为true

                Node h = head;  

                if (h != null && h.waitStatus != 0)

                    unparkSuccessor(h);

                return true;

            }

            return false;

        }

    接下来分析tryRelease()方法:

    protected final boolean tryRelease(int releases) {  // releases=1

                int c = getState() - releases;        //getState()

                if (Thread.currentThread() != getExclusiveOwnerThread())  //当前执行线程线程是否是独占锁持有线程

                    throw new IllegalMonitorStateException();

                boolean free = false;

                if (c == 0) {  // 该线程持有锁的次数已经全部被释放了

                    free = true;

                    setExclusiveOwnerThread(null);  //设置独占锁的持有线程为null

                }

                setState(c);  //设置设置加锁次数为c

                return free;  //返回独占锁是否被释放了;

            }

     下面分析 unparkSuccessor(h); 这个方法:

    private void unparkSuccessor(Node node) {   //node =head  表头

           

            int ws = node.waitStatus;  //  表头等待状态

            if (ws < 0)      

                compareAndSetWaitStatus(node, ws, 0);

            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);

        }

    这个方法的作用是唤醒下一个等待线程;

  • 相关阅读:
    毕业设计进度3
    毕业设计进度2
    毕业设计进度1
    hadoop环境搭建
    大数据之kettle安装
    服务化管理和治理框架的技术选型
    云时代架构读后感五
    云时代架构读后感四
    毕业设计2019/10/24至2019/10/31进度计划
    IT架构的本质
  • 原文地址:https://www.cnblogs.com/beppezhang/p/11214683.html
Copyright © 2011-2022 走看看