关于java:话说-ReentrantLock源码

43次阅读

共计 1687 个字符,预计需要花费 5 分钟才能阅读完成。

之前文章写 AQS 的时候有说过偏心锁的代码 这里以非偏心锁来看一下

面试的时候设计模式:模板办法 在 AQS 里体现的酣畅淋漓,你要是从设计模式扯到这里,而后你正好又看过 AQS 在 ReentrantLock 中的实现,那你就能够让面试官眼前一亮

Lock lock  =  new ReentrantLock(false);
lock.lock();

/**
     * 申请锁
     *
     * <p>Acquires the lock if it is not held by another thread and returns
     * immediately, setting the lock hold count to one.
     *  如果没有其余线程持有这个锁,就马上返回,并设置锁持有数为 1
     * <p>If the current thread already holds the lock then the hold
     * count is incremented by one and the method returns immediately.
     * 如果以后线程持有锁,就吧持有数量 +1(可重入)而后立刻返回 
     * <p>If the lock is held by another thread then the
     * current thread becomes disabled for thread scheduling
     * purposes and lies dormant until the lock has been acquired,
     * at which time the lock hold count is set to one.
     * 如果锁被其余线程持有,以后线程对于调度就不可用,而后睡着,直到获取锁,而后把锁持有数改为 1 
     */
// ReentrantLock.class
public void lock() {sync.lock();
}
// NonfairSync.class
final void lock() {
    // 先抢一下(上一篇说的:小强二话不说先看看能不能跟老板选饼)if (compareAndSetState(0, 1))
        setExclusiveOwnerThread(Thread.currentThread());
    else
        // 如果没有抢到 再去申请
        acquire(1);
}
// AbstractQueuedSynchronizer.class
 public final void acquire(int arg) {
        // 这个 tryAcquire 会再抢一次(小强还抱着插队的空想)if (!tryAcquire(arg) &&
            // 抢不到 就后边排队吧
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();}

 // ReentrantLock.class
 protected final boolean tryAcquire(int acquires) {return nonfairTryAcquire(acquires);
 }

// ReentrantLock.class 
// 这里须要理解 AQS 我其余文章有写 能够去看
final boolean nonfairTryAcquire(int acquires) {
    // 获取以后线程
    final Thread current = Thread.currentThread();
    // 获取 state 标记位
    int c = getState();
    if (c == 0) {
        // 如果没有线程持有尝试获取锁(小强看见没人跟老板谈话 间接插队买饼)if (compareAndSetState(0, acquires)) {setExclusiveOwnerThread(current);
            return true;
        }
    }
    // 如果有线程持有  看一下是不是本人
    else if (current == getExclusiveOwnerThread()) {
        // 如果是本人就批改持有数
        int nextc = c + acquires;
        // 超过最大锁数 
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

有问题能够留言哦,也能够公众号留言(回复快):

正文完
 0