JUC--ReentrantLock

ReentrantLock基于AQS,它实现了公平锁和非公平锁,在开发中可以用它对共享资源进行同步,此外,和synchronized一样,ReentrantLock支持可重入锁,但ReentrantLock在调度上更灵活。
在这里插入图片描述
首先来看ReentrantLock的继承关系,ReentrantLock实现了Lock接口。在面向对象的概念中,既然ReentrantLock是Lock的一种具体实现,呢么它必然拥有Lock的抽象意义。

Lock只是定义了一些方法的语义,规定了它的 实现类需要满足这些语义。

关于ReentrantLock类的源码,我们关注一下三个方面:

  • 属性:sync
  • 内部类:Sync,NofairSync,FairSync
  • 方法:
    继承/实现方法:实现Lock的方法
    私有方法

属性

ReentrantLock只有一个属性:Sync类型的变量sync。sync被final修饰,意味着一旦初始化,就不可修改引用了。那么它的初始化时机是什么时候?

private final Sync sync;

在ReentrantLock构造器中:

	public ReentrantLock() {
   
        sync = new NonfairSync();
    }
    public ReentrantLock(boolean fair) {
   
        sync = fair ? new FairSync() : new NonfairSync();
    }

默认非公平锁。

内部类

Sync

abstract static class Sync extends AbstractQueuedSynchronizer {
   
        private static final long serialVersionUID = -5179523762034025860L;

        /**
         * Performs {@link Lock#lock}. The main reason for subclassing
         * is to allow fast path for nonfair version.
         */
        abstract void lock();

        /**
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        final boolean nonfairTryAcquire(int acquires) {
   
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
   
                if (compareAndSetState(0, acquires)) {
   
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
   
                int nextc = c + acquires;
           
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值