ReentrantLock

目录

Lock:

属性:

Sync: 继承了AQS 的抽象类

NonfairSync

FairSync:

ReentrantLock 构造方法:

lock 方法: 阻塞式获取锁

lockInterruptibly 方法:

acquireInterruptibly方法:

tryLock 尝试1次获取锁

tryLock带有超时时间的获取锁:

调用AQS 中的tryAcquireNanos 方法

doAcquireNanos 方法:

unlock释放锁

AQS release方法

AQS unparkSuccessor 方法:

SYNC 中tryRelease方法

newCondition() 方法:

getHoldCount() 方法:

isLocked() 判断当前是否已锁定

isFair方法 判断当前锁是否为公平所 是返回true

getOwner() 方法 返回持有当前锁的线程 如未持有锁 返回null

hasQueuedThreads()方法 队列中是否有其他线程在等待锁

hasQueuedThread()方法 判断当前队列中是否有指定线程

getQueueLength() 方法 获得队列有效节点的长度

getQueuedThreads() 获得队列中的所有有效线程

hasWaiters() 判断 当前condition上 是否有等待者

getWaitQueueLength() 判断指定condition上对应的AQS 队列中有状态为wait的节点的数目

getWaitingThreads 获得队列中等待状态的所有线程


实现了Lock接口

Lock:

public interface Lock {

    // 阻塞的获取锁接口
    void lock();
		
    // 可中断的  获取锁的接口
    void lockInterruptibly() throws InterruptedException;
		
    // 非阻塞式的 获取锁接口
    boolean tryLock();
		
    // 带有超时时间的 获取锁接口
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
		
    // 释放锁接口
    void unlock();

    /**
     * 返回一个新的 Condition 实例 这个实例与当前lock 实例相关联
     * Returns a new {@link Condition} instance that is bound to this
     * {@code Lock} instance.
     * 当前线程必须拿到lock锁   才能 在Condition上等待
     * <p>Before waiting on the condition the lock must be held by the
     * current thread.
     * 调用Condition#await()方法 将在等待之前 原子的 释放Condition对应的锁 
     * A call to {@link Condition#await()} will atomically release the lock
     * before waiting and re-acquire the lock before the wait returns.
     *
     * <p><b>Implementation Considerations</b>
     * Condition 的操作实现依赖于 Lock的实现
     * <p>The exact operation of the {@link Condition} instance depends on
     * the {@code Lock} implementation and must be documented by that
     * implementation.
     * // 为当前锁实例 返回一个新的Condition 实例
     * @return A new {@link Condition} instance for this {@code Lock} instance
     * @throws UnsupportedOperationException if this {@code Lock}
     *         implementation does not support conditions
     */
    Condition newCondition();
}

属性:

    private final Sync sync;

Sync: 继承了AQS 的抽象类

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) {
            		// 尝试cas 修改同步值拿到锁
                if (compareAndSetState(0, acquires)) {
                		// 拿锁成功 设置当前线程为独占锁
                    setExclusiveOwnerThread(current);
                    // 返回成功
                    return true;
                }
                // cas失败 返回失败
            }
            // 重入实现  如当前线程 与 已获得锁的独占线程为 同一个线程
            else if (current == getExclusiveOwnerThread()) {
            		// 计算下次的state值
                int nextc = c + acquires;
                // 溢出 抛异常
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                // 更新state  因为当前线程为 独占线程  所以 state 不会被另外的线程更改  直接set满足同步要求
                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;
                // 锁将释放 将独占线程置null
                setExclusiveOwnerThread(null);
            }
            // 释放锁  或部分锁
            setState(c);
            // 返回锁是否已释放完毕 释放完毕true  否则false
            return free;
        }
        
				// 判断独占锁持有线程是否为当前线程
        protected final boolean isHeldExclusively() {
            // While we must in general read state before owner,
            // we don't need to do so to check if current thread is owner
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

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

        // Methods relayed from outer class
				
        // 获取当前锁持有线程
        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }
				// 当前线程不是持有锁线程 返回state值  否则返回0
        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }
				// 是否已上锁
        final boolean isLocked() {
            return getState() != 0;
        }

        /**
         * Reconstitutes the instance from a stream (that is, deserializes it).
         */
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

NonfairSync

    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        // 阻塞式获取锁
        final void lock() {
        		// cas成功 
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
            		// 调用AQS 方法阻塞式获取锁 直到成功
                acquire(1);
        }
				
        // 重写tryAcquire方法   为acquire方法服务
        protected final boolean tryAcquire(int acquires) {
        		// 非公平的获取锁
            return nonfairTryAcquire(acquires);
        }
    }

FairSync:

/**
     * Sync object for fair locks
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
        		// 与 非公平差别之一 不直接cas尝试 而是直接调用父类acquire方法
            acquire(1);
        }

        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
            		// 只有队列中无前继节点 才执行cas  如cas成功 获取到锁
                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;
        }
    }

ReentrantLock 构造方法:

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

		// 用户选择使用 公平锁 or 非公平锁
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

lock 方法: 阻塞式获取锁

// 调用静态内部类中的lock方法
    public void lock() {
        sync.lock();
    }

lockInterruptibly 方法:

// 线程中断排除中断异常
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

acquireInterruptibly方法:

 public final void acquireInterruptibly(int arg)
            throws InterruptedException {
        // 如线程中断 抛出中断异常
        if (Thread.interrupted())
            throw new InterruptedException();
        // 尝试获取锁
        if (!tryAcquire(arg))
        		// 失败执行队列等待 直到获取成功  或中断抛出中断异常
            doAcquireInterruptibly(arg);
    }

AQS中doAcquireInterruptibly 方法:

    private void doAcquireInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return;
                }
                //如等待后 被唤醒后 线程已中断  抛出中断异常
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt()) 
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

tryLock 尝试1次获取锁

    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

tryLock带有超时时间的获取锁:

    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

调用AQS 中的tryAcquireNanos 方法

public final boolean tryAcquireNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        return tryAcquire(arg) ||
            doAcquireNanos(arg, nanosTimeout);
    }

doAcquireNanos 方法:

	private boolean doAcquireNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (nanosTimeout <= 0L)
            return false;
        // 超时的截止实现
        final long deadline = System.nanoTime() + nanosTimeout;
        // 创建新节点 并加入到队列中
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
            		// 获得节点的前继
                final Node p = node.predecessor();
                // 如前继节点为头结点 则cas 获取锁
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    // 返回成功
                    return true;
                }
                // 获取剩余超时时间
                nanosTimeout = deadline - System.nanoTime();
                // 已超时返回失败
                if (nanosTimeout <= 0L)
                    return false;
                // 可以挂起 且当前 超时剩余时间大于 自旋时间阈值1000纳秒
                if (shouldParkAfterFailedAcquire(p, node) &&
                    nanosTimeout > spinForTimeoutThreshold)
                    // 挂起剩余超时时间
                    LockSupport.parkNanos(this, nanosTimeout);
                if (Thread.interrupted())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

unlock释放锁

public void unlock() {
        sync.release(1);
    }

线程释放锁过程:

AQS release方法

public final boolean release(int arg) {
    		// 如尝试释放锁成功
        if (tryRelease(arg)) {
        		// 拿到头结点
            Node h = head;
            // 如头结点不为null 且 等待状态 已初始化了
            if (h != null && h.waitStatus != 0)
            		// 唤醒后继节点
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

唤醒节点:

AQS unparkSuccessor 方法:

		private void unparkSuccessor(Node node) {
  			
        int ws = node.waitStatus;
        // 如头结点状态 不为取消和未初始化状态
        if (ws < 0)
        		// 将头结点状态重置为0
            compareAndSetWaitStatus(node, ws, 0);

        // 获得当前节点的后继节点
        Node s = node.next;
        // 如后继节点为null 或 为取消状态
        if (s == null || s.waitStatus > 0) {
            s = null;
            // 从尾巴节点 向前遍历 拿到最靠前面的非取消状态有效节点  直到 节点为null 或 节点等于当前节点
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        // 如有等待锁 且有效节点
        if (s != null)
        		// 执行唤醒线程
            LockSupport.unpark(s.thread);
    }

SYNC 中tryRelease方法

	// 尝试释放锁
        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;
                // 锁将释放 将独占线程置null
                setExclusiveOwnerThread(null);
            }
            // 释放锁  或部分锁
            setState(c);
            // 返回锁是否已释放完毕 释放完毕true  否则false
            return free;
        }

newCondition() 方法:

		public Condition newCondition() {
    		// 调用sync 的方法
        return sync.newCondition();
    }
    
    final ConditionObject newCondition() {
    		// 创建AQS 中内部类ConditionObject 的实例
    		return new ConditionObject();
    }

getHoldCount() 方法:

查询当前线程持有的锁数目

    public int getHoldCount() {
    		// 调用sync类的getHoldCount() 方法
        return sync.getHoldCount();
    }

// 调用sync类的getHoldCount() 方法

    final int getHoldCount() {
    		// 判断当前 线程是否是持有锁的线程  如是 返回state 否则返回0
    		return isHeldExclusively() ? getState() : 0;
    }

isLocked() 判断当前是否已锁定

      public boolean isLocked() {
      		// 调用sync的 isLocked方法
      		return sync.isLocked();
      }
      
      final boolean isLocked() {
            return getState() != 0;
      }

isFair方法 判断当前锁是否为公平所 是返回true

代码块

public final boolean isFair() {
        return sync instanceof FairSync;
    }
 

 

 

getOwner() 方法 返回持有当前锁的线程 如未持有锁 返回null

代码块

protected Thread getOwner() {
        return sync.getOwner();
    }
    
 

 

hasQueuedThreads()方法 队列中是否有其他线程在等待锁

代码块

public final boolean hasQueuedThreads() {
        // 调用sync 中的方法
        return sync.hasQueuedThreads();
    }

    如头结点不等于尾巴节点 返回true  也即有等待线程
    public final boolean hasQueuedThreads() {
        return head != tail;
    }
 

 

hasQueuedThread()方法 判断当前队列中是否有指定线程

代码块

public final boolean hasQueuedThread(Thread thread) {
        // 调用sync的方法
        return sync.isQueued(thread);
    }

    // 从尾巴遍历联表 判断指定线程是否在队列中
    public final boolean isQueued(Thread thread) {
        if (thread == null)
            throw new NullPointerException();
        for (Node p = tail; p != null; p = p.prev)
            if (p.thread == thread)
                return true;
        return false;
    }
    
 

 

getQueueLength() 方法 获得队列有效节点的长度

代码块

public final int getQueueLength() {
        return sync.getQueueLength();
    }

    public final int getQueueLength() {
        int n = 0;
        for (Node p = tail; p != null; p = p.prev) {
            // 如果节点中线程有效 则认为是有效节点
            if (p.thread != null)
                ++n;
        }
        return n;
    }
    
 

 

getQueuedThreads() 获得队列中的所有有效线程

代码块

protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    public final Collection<Thread> getQueuedThreads() {
        ArrayList<Thread> list = new ArrayList<Thread>();
        for (Node p = tail; p != null; p = p.prev) {
            Thread t = p.thread;
            if (t != null)
                list.add(t);
        }
        return list;
    }
    
 

 

hasWaiters() 判断 当前condition上 是否有等待者

代码块

public boolean hasWaiters(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        // 调用AQS 的方法 判断当前condition上是否 有waiters
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    public final boolean hasWaiters(ConditionObject condition) {
        // 判断此condition是否被当前线程拥有
        if (!owns(condition))
            throw new IllegalArgumentException("Not owner");
        // 调用AQS 中condition内部类 的haswaiters()方法
        return condition.hasWaiters();
    }
    
 
 

 

AQS 中condition 的 hasWaiters 方法

代码块

 protected final boolean hasWaiters() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
                // 如果AQS 中有 waitstatus为 CONDITION 的节点
                if (w.waitStatus == Node.CONDITION)
                    return true;
            }
            return false;
        }
       
 

 

getWaitQueueLength() 判断指定condition上对应的AQS 队列中有状态为wait的节点的数目

代码块

public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        // 调用AQS 的方法  获得队列中 wait节点的长度
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    public final int getWaitQueueLength(ConditionObject condition) {
        // 判断此condition是否被当前线程拥有
        if (!owns(condition))
            throw new IllegalArgumentException("Not owner");
        // 调用AQS 中condition内部类 getWaitQueueLength()方法
        return condition.getWaitQueueLength();
    }
    
 

 

AQS 中condition 的 getWaitQueueLength 方法

代码块

protected final int getWaitQueueLength() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            int n = 0;
            // 统计队列中 状态为CONDITION  的节点数目
            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
                if (w.waitStatus == Node.CONDITION)
                    ++n;
            }
            return n;
        }
        
 

 

getWaitingThreads 获得队列中等待状态的所有线程

代码块

 protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        // 通过sync 调用AQS 中的方法
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }
   
 

 

AQS getWaitingThreads()方法:

代码块

public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
        if (!owns(condition))
            throw new IllegalArgumentException("Not owner");
        return condition.getWaitingThreads();
    }
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值