关于java:JDK8-new-ReentrantLock加锁流程二

new ReentrantLock(true);加锁流程:

protected final boolean tryAcquire(int acquires) {
    //获取以后线程
    final Thread current = Thread.currentThread();
    //获取state值
    int c = getState();
    //还没有线程占用
    if (c == 0) {
        //!(头节点和尾节点不是一个节点 && (头节点的next -> NULL 或者 头节点.next节点 不是 以后线程 ))
        //也就是说,头尾是一个节点 或者 头节点.next节点的线程是以后线程
        if (!hasQueuedPredecessors() &&
            //cas 0 -> 1
            compareAndSetState(0, acquires)) {
            /设置独占线程
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    //以后线程等于独占线程
    else if (current == getExclusiveOwnerThread()) {
        //state值+1
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        //从新赋值 state 值
        setState(nextc);
        return true;
    }
    //否则返回false
    return false;
}

如果取得锁失败,和JDK8 new ReentrantLock()加锁流程(一)中流程一样!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理