AQS源码阅读

AQS是用来构建锁或者其它同步器组件的重量级基础框架及整个JUC体系的基石,通过内置的FIFO队列来完成资源获取线程的排队工作,并通过一个int类变量
表示持有锁的状态。

我将以ReentrantLock为切入点,阅读ASQ源码。

:ReentrantLock默认是线程不安全的,当然也可以设置为线程安全。

一、lock.lock();

        final void lock() {
       //通过CAS尝试加锁,当获到独占锁时,status=1,
if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else //尝试获取锁
          acquire(
1); }
    public final void acquire(int arg) { //arg = 1
        if (!tryAcquire(arg) && //这里用到了模板设计模式
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

tryAcquire()

复制代码
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState(); //0
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {//尝试获取锁,获取成功返回true
                    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;//没抢到独占锁,返回false
        }
复制代码

当尝试获取锁失败时,需要加入等待队列,但加入等队列的时候,还会进行对独占锁的抢占

先加入等待addWaiter(Node.EXCLUSIVE);(EXCLUSIVE为null)

复制代码
    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; }
复制代码

 

 

 

 acquareQueue()

复制代码
final boolean acquireQueued(final Node node, int arg) { //node = t, arg = 1
        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) && //p(哨兵节点)waitstatus设置为SIGNAL (-1) parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); //将t节点的等待状态设置为1 } }
复制代码

除了首个进入队列的节点的waitstatus=1,后续加入的节点都为0,且不会抢夺独占锁

 

 解锁lock.unlock

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

 

posted @   金玉良猿  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示