AQS实现ReentrantLock和CountLatchDown详解

前言:AQS看懂了,来了解一下ReentrantLock、CountLatchDown大概的实现原理,看这篇文章之前需要把AQS了解清楚,如果不了解可以去看https://blog.csdn.net/q610376681/article/details/108917792

参考:https://blog.csdn.net/Mutou_ren/article/details/103827337

目录

第一章 基于AQS实现ReentrantLock

1.1 lock

1.2 unlock

第二章 基于AQS实现CountLatchDown

1.1 await

1.2 countDown

 

第三章 ReentrantLock和booleanlock


第一章 基于AQS实现ReentrantLock

在ReentrantLock中依靠一个state来表示锁的状态,当state为0表示没有线程获取了锁,当state>0表示有线程获取了锁,数值如果为2表示有线程重入了一次锁,以此类推等等。

private volatile int state;

1.1 lock

在加锁时先尝试用CAS将状态改为1,如果变为了1,则加锁成功,如果并没有改变成功,则尝试获取资源。

final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

 可以看到,流程就转到了AQS非公平锁的获取环节,这里我们不再赘述非公平锁的上锁流程,主要说一下ReentrantLock实现的tryAcquire。

public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

 可以看到,如果状态是0,则用CAS尝试更改状态为1,如果更改成功则获取到锁,如果当前线程已持有锁,则将状态加1,若以上都不满足,则返回获取锁失败。

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;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

 

1.2 unlock

在解锁函数中调用了unlock,unlock调用了release,这里不再对阻塞流程进行说明,主要分析一下tryRelease。

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

public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

在资源的释放函数中, 如果当前线程没获得锁则抛出异常,如果获取了锁则将状态值减一,如果减完后状态值变成了0,则表示已没有线程获得锁,并返回释放资源成功,如果没变成0,则返回释放资源失败。

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;
        }

 

 

第二章 基于AQS实现CountLatchDown

先看一下CountLatchDown的使用,这个我懒得敲了,直接复制这位博主的了,https://blog.csdn.net/Mutou_ren/article/details/103827337,大概看一下就行。

这个类的作用大致就是创建CountLatchDown时传入一个数值假设为a,调用await会阻塞调用的线程,当调用a次countDown()函数后,被阻塞的线程恢复执行。

状态值表示的是还有几个在运行的线程,每运行完一个线程调用一次countDown使状态值减一,当状态值被减成0的时候,被阻塞的线程恢复运行。

public class TestCountDownLatch {

    public static CountDownLatch countDownLatch = new CountDownLatch(3);

    public static void main(String[] args) throws InterruptedException {
        for (int i=0;i<3;i++){
            new Thread(new Task()).start();
        }
        System.out.println("线程启动结束,主线程进入等待状态");
        countDownLatch.await();
        System.out.println("主线程结束");
    }
}

class Task implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+" task ");
            TestCountDownLatch.countDownLatch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

1.1 await

大致就是调用await会去请求共享资源,根据状态值是否为0来决定是否能获取到资源,当状态值为0时获取资源成功,如果请求共享资源失败则阻塞线程。

public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
​
protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }


private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

1.2 countDown

可以看到当调用countDown的时候,状态值将会被减一,如果减完后状态值为0,则返回true表示释放成功,

public void countDown() {
        sync.releaseShared(1);
    }

public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }

protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }

释放成功后则会调用doReleaseShared唤醒后面的线程。

private void doReleaseShared() {
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

 

第三章 ReentrantLock和booleanlock

在这里说一下booleanlock,这个是我看Java高并发编程详解看到的,它用wait和notify比较简短的代码实现了ReentrantLock的功能,而ReentrantLock的实现是基于AQS的,正常情况下面试官问ReentrantLock的实现原理都是在问基于AQS的那种,关于booleanlock使用wait和notify实现的ReentrantLock感兴趣的可以参考:

https://blog.csdn.net/q610376681/article/details/107755183   3.1章

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值