AbstractQueueSynchronizer

1、CountDownLatch、ReentrantLock等并发包中的同步底层实现都是用的AQS:AbstractQueueSynchronizer

2、AQS包含资源state数字,阻塞的时候说明state不等于0

3、获取到锁,将state+1,释放锁的时候-1,当state等于0说明可以获取到锁

4、CountDownLatch初始化将state设置为N,主线程调用await方法阻塞,也就是判断state是否为0,此时说明有N个线程同时执行,每个线程执行完countDown一次,当state减为0的时候,await方法可继续执行。

5、AQS通过CAS修改state的值,CompareAndSwap,调用了C语言的Unsafe类的cas方法。

//直接获取锁,获取失败进入队列FIFO
public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

//进入链表尾部
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;
    }

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

//tryRelease需要自己实现,AQS没有提供实现类,排他锁和共享锁不一样,下面以ReentrantLock排他锁为例
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;
        }

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); //唤醒线程
    }

//当头部线程释放锁后,唤醒后续线程
public static void unpark(Thread thread) {
        if (thread != null)
            UNSAFE.unpark(thread);  //C语言底层调用唤醒线程
    }

//共享锁,以CountDownLatch的实现为例,可以多个线程调用await方法,共享这个锁
protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

 

图来自:http://ifeve.com/introduce-abstractqueuedsynchronizer/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值