Zhou Study hard, improve every day.

AQS源码阅读

2020-05-04
本文 519 字,阅读全文约需 2 分钟

1.AQS结构

1588568017694

2.方法阅读

多个节点同时去争夺state 用cas的方法

public static void main(String[] args) {
        Lock lock = new ReentrantLock();

        lock.lock();

        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

}

执行流程

1588570694968

情形2(再次获得该锁)

1588572575513

加锁的流程
protected final boolean compareAndSetState(int expect, int update) {
	return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

Similar Posts

下一篇 Linux链接

Comments