Java并发同步器AQS(AbstractQueuedSynchronizer)

换AQS中的数据结构-节点和同步队列

同步器AQS中有两个参数:head,tail,分别指头节点,尾节点

节点Node中有两个参数:prev,next,分别指前一个节点,后一个节点

1.节点加入到同步队列

ReentrantLock代码:下面以ReentrantLock分析

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

AQS代码:这里就是修改状态,设置排它,不成功就执行acquire(1)尝试获取锁

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

这里很简单,没有什么特别的,就是tryAcquire()--这个方法AQS没有实现是由ReentrantLock实现的,返回true则说明拿到锁,如果返回false执行&&后面的acquireQueued()加入队列;

addWaiter()方法将节点通过CAS操作加入到上图中同步队列中的尾节点

AQS代码:

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;
        //说明:先来次快速的判断,是否能加入到尾节点;失败执行enq(CAS操作)
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
}

AQS代码:

    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)) {//CAS操作
                    t.next = node;
                    return t;
                }
            }
        }
    }

2.首节点的变化

AQS代码:

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)) {//判断前一个节点是否是头结点,如果是则尝试拿锁
                    //拿锁成功后,设置为头节点,并且将前一个节点置为null
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                //否则判断是否应该被阻塞,返回true(说明具有拿锁的权利了),执行parkAndCheckInterrupt阻塞。除了异常等待释放锁的时候唤醒
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

ReentrantLock代码:释放锁

    public void unlock() {
        sync.release(1);
    }
    public final boolean release(int arg) {
        if (tryRelease(arg)) {//返回true,说明释放锁了
            Node h = head;//找到头节点
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);//唤醒后继节点
            return true;
        }
        return false;
    }

 唤醒后继节点,需要判断后继节点是否为CANCELLED状态

线程在队列中的状态枚举:

CANCELLED:值为1,表示线程的获锁请求已经“取消”

SIGNAL:值为-1,表示该线程一切都准备好了,就等待锁空闲出来给我

CONDITION:值为-2,表示线程等待某一个条件(Condition)被满足

PROPAGATE:值为-3,当线程处在“SHARED”模式时,该字段才会被使用上

初始化Node对象时,默认为0

    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;
        //这里是判断是出于CANCELLED状态,如果是则从尾部往前找不是CANCELLED状态的节点
        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);//唤醒
    }

Condition分析

一个Condition包含一个等待队列

同步队列与等待队列

await方法

public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();//加入Condition
            int savedState = fullyRelease(node);//释放锁
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);//在Condition 中等待
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            //被唤醒之后加入同步队列自旋争抢锁
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
}

signal方法  唤醒Condition的第一个加入到同步队列取重新争抢锁

        public final void signal() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;//Condition中的first
            if (first != null)
                doSignal(first);
        }
        private void doSignal(Node first) {
            do {
                if ( (firstWaiter = first.nextWaiter) == null)
                    lastWaiter = null;
                first.nextWaiter = null;
            } while (!transferForSignal(first) &&
                     (first = firstWaiter) != null);
        }
    final boolean transferForSignal(Node node) {
        /*
         * If cannot change waitStatus, the node has been cancelled.
         */
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;

        /*
         * Splice onto queue and try to set waitStatus of predecessor to
         * indicate that thread is (probably) waiting. If cancelled or
         * attempt to set waitStatus fails, wake up to resync (in which
         * case the waitStatus can be transiently and harmlessly wrong).
         */
        //加入同步队列的尾部
        Node p = enq(node);
        int ws = p.waitStatus;
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值