ReentrantLock简单图解学习

写这篇文章是让自己对AQS和ReentrantLock加深理解,需要配合之前的文章一起学习。

AQS(AbstractQueuedSynchronizer)初学

java ReentrantLock(可重入锁)初学

假设有3个线程A、B、C都调用lock.lock()方法获取锁,ReentrantLock 默认的构造方法调用的是非公平锁

public ReentrantLock() {
        sync = new NonfairSync();

}

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

        final void lock() {
            if (compareAndSetState(0, 1))//  
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);//
        }
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);// 
        }

    }

①:假设线程A获取到锁往下执行,当线程B调用lock()方法的时候调用①失败 执行方法②(此方法在父类AQS中)代码如下:

 public final void acquire(int arg) {

        if (!tryAcquire(arg) //

            &&acquireQueued(addWaiter(Node.EXCLUSIVE), arg))//

            selfInterrupt();

    }

tyAcquire():由自定义锁实现在这里实际就是方法③ 主要就是通过改变state的状态来获取锁,没有获取到锁的话就执行方法⑤中的addWaiter()

 private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }

线程B执行到此此时tail还是null 所以执行方法⑦ 循环CAS直到成功返回

private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize

                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {//

                    t.next = node;
                    return t;
                }
            }
        }

    }

此时tail是null 必须先进行队列的初始化设置队列的头结点:成功以后如下图所示


方法⑨成功以后如下图所示:


结束循环继续执行方法⑤中的acquireQueued()方法:

final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {//

                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&//

                    parkAndCheckInterrupt())//

                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }

    }

执行方法⑩p节点为头节点再次进行获取锁的操作(因为此时获取A线程已经执行完毕或者A线程取消了),假设此时线程A还没有结束执行方法

将head节点的waitStatus设置为SIGNAL(-1)返回true继续执行方法⑫将线程B挂起

假设线程C和线程B一样的流程此时的状态图如下:


此时线程A执行完毕调用了 unlock()方法(实际上是调用的AQS的release方法):

public final boolean release(int arg) {
        if (tryRelease(arg)) {//

            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);//

            return true;
        }
        return false;
    }

调用方法⑬通过改变state释放锁,继续执行方法

private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);


        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;//

        if (s == null || s.waitStatus > 0) {
            s = 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);//唤醒线程

    }

此时的Node是指向头节点的,通过s=node.next 将s结点执行线程B的结点将线程B唤醒,然后线程B继续执行acquireQueued()方法里面的方法

进入方法⑩后将会重新设置头节点将原来的头节点删除将原来线程B所在的结点设置为头节点,如下图所示:


线程B执行完以后也会执行unlock()方法按上述的流程将线程C唤醒继续执行。

总结:此文章是假设三个线程按照顺序执行并且中间抢占资源都没有成功也没有发生中断,只是使用一种最简单的方法来理解ReentrantLock的流程。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值