ReentrantLock

 

 

package java.util.concurrent.locks;
import java.util.concurrent.TimeUnit;
import java.util.Collection;


public class ReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    /** Synchronizer providing all implementation mechanics */
    private final Sync sync;

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

      
        abstract void lock();

       
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            //还没有线程持有锁
            if (c == 0) {
                //设置成功返回true,失败说明其它线程抢先一步,返回false
                //这里是非公平模式,比较成功就获取锁,而公平模式会查看等待队列是否
                //有线程排队,如果有就不能获取锁
                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;
        }
        
        //尝试释放锁
        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            //释放锁的线程必须是已获取锁的线程!!
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            //直接设置,无需比较,因为当前线程已经获取到锁,不会有竞争
            setState(c);
            //是否完全释放了所有许可
            return free;
        }

        //返回是否是当前线程拥有锁
        protected final boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        //创建Condition对象
        final ConditionObject newCondition() {
            return new ConditionObject();
        }

        
        //返回拥有锁的线程
        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

        //返回拥有锁的线程锁定的次数
        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        //是否有线程持有了锁
        final boolean isLocked() {
            return getState() != 0;
        }

       
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

    //非公平同步器
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

       
        final void lock() {
            //抢占式的,设置成功就锁定
            //相比之下,公平模式总先查看等待队列中是否有线程排队,如果有,总是返回失败,
            //没有再查看状态是否是0并设置
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                //尝试获取,失败则挂起线程
                acquire(1);
        }

        //由当前子类重写的模板方法,有acquire方法调用,如果尝试后期成功直接返回,
        //失败将导致线程挂起
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                //非公平模式下的lock与公平模式的lock的区别就是少了这一个判断
                //已有线程等待获取锁,那么当前线程也应该获取失败,继续排队
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
    }

    //默认非公平
    public ReentrantLock() {
        sync = new NonfairSync();
    }

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

    //调用实现了模板类AbstractQueuedSynchronizer的sync的lock方法
    //获取一个锁
    public void lock() {
        sync.lock();
    }

    //获取一个锁,可响应中断
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    //尝试获取一个锁,成功返回true,否则false
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

    //超时时间内尝试获取一个锁,成功返回true,否则false
    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    //直接调用模板类AbstractQueuedSynchronizer的release方法
    //释放一个锁
    public void unlock() {
        sync.release(1);
    }

   
    public Condition newCondition() {
        return sync.newCondition();
    }

    //调用getHoldCount返回拥有锁的线程锁定的次数
    public int getHoldCount() {
        return sync.getHoldCount();
    }

    //是否是当前线程获取的锁
    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

   //是否有线程获取锁,判断state值非0
    public boolean isLocked() {
        return sync.isLocked();
    }

    //是否是公平模式还是抢占模式
    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    //返回获取锁的线程,可能是null
    protected Thread getOwner() {
        return sync.getOwner();
    }

    //是否有线程在等待锁,链表不为空
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    //在等待锁的线程中是否包含指定线程
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    //返回等待锁的线程个数
    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    //返回等待锁的所有线程
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }


    //以下方法与Condition对象相关
    //Condition 对象的条件队列不为空(不包含取消的节点)
    public boolean hasWaiters(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    //Condition 对象的条件队列节点个数(不包含取消的节点)
    public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

     //返回Condition 对象的条件队列中的所有线程(不包含取消的节点)
    protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

   
    public String toString() {
        Thread o = sync.getOwner();
        return super.toString() + ((o == null) ?
                                   "[Unlocked]" :
                                   "[Locked by thread " + o.getName() + "]");
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值