美文网首页
看!源码之ReentrantLock非公平锁

看!源码之ReentrantLock非公平锁

作者: starskye | 来源:发表于2020-12-21 14:40 被阅读0次

公平锁讲完再讲非公平锁很简单,如果未看过公平锁的文章请阅读之前的文章后再阅读当前文章,否则会导致阅读障碍。

//非公平锁获取锁
final void lock() {
    //很暴力直接尝试设置当前所得状态如果设置成功则设置当前线程为持有锁
    if (compareAndSetState(0, 1))
        setExclusiveOwnerThread(Thread.currentThread());
    else
        //否则调用Sync的实现
        acquire(1);
}
//在acquire方法中有调用tryAcquire 而此处重写了此方法
protected final boolean tryAcquire(int acquires) {
      //此方法调用的nonfairTryAcquire方法
     return nonfairTryAcquire(acquires);
}
//非公平锁获取方式可以对照公平锁
final boolean nonfairTryAcquire(int acquires) {
    //获取当前线程
    final Thread current = Thread.currentThread();
    int c = getState();
    //状态如果为0
    if (c == 0) {
        //直接设置锁获取状态,在公平锁是在设置状态前还进行检查是否有Node在队列
        //如果在队列则不再获取锁否则也是直接获取锁 此处逻辑不一样从而形成了非公平锁
        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;
}

到此非公平实现结束,省略了一些以在公平锁内讲解过得内容。

相关文章

网友评论

      本文标题:看!源码之ReentrantLock非公平锁

      本文链接:https://www.haomeiwen.com/subject/arvoshtx.html