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

    }

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

posted @ 2019-07-19 17:36  beppezhang  阅读(276)  评论(0编辑  收藏  举报