AQS

瘦欲@ 提交于 2020-08-17 03:47:06

jdk1.8版本

ReentantLock内部使用的是AQS,AQS的基础实现是CAS+Volatile;

调用lock方法,会调用Sync类中的lock()方法

public void lock() {
    sync.lock();
}

Sync中的lock()方法,使用compareAndSetState

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

调用AbstractQueuedSynchronizer(AQS)中的compareAndSetState,

protected final boolean compareAndSetState(int expect, int update) {
    // See below for intrinsics setup to support this
    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}

调用unsafa.compareAndSwapInt进入到static final class NonfairSync extends Sync 中的lock方法,设置排他线程,参数为当前线程,如果返回true表示上锁成功,当前线程获取锁。想要获取acquire(1),开启一个线程,走一下看看内容

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

执行acquire,会调用AbstractQueuedSynchronizer中的方法

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

if判断中第一个方法,当tryAcquier(1),尝试获取一个非公锁,tryAcquier(1)返回false将执行acquireQueued放啊

protected final boolean tryAcquire(int acquires) {
    return nonfairTryAcquire(acquires);
}

调用ReentrantLock中的nonfaieTryAcquire(1),,获取当前的状态getState(),State是使用volatile修饰,State标识锁的重入数

final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();//获取当前线程
    int c = getState();//获取状态,因为已经有一个线程上锁,所以返回值是1
    if (c == 0) {
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);//如果返回0,current使用CAS把自己设置为独占线程上锁成功
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {//如果当前独占线程就是当前线程,State+1
        int nextc = c + acquires;
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

acquireQueued(addWaiter(Node.EXCLUSIVE), arg)方法,字面意思是创建一个独占节点加入等待队列中,然后尝试获取队列

Node(Thread thread, Node mode) {     // Used by addWaiter
    this.nextWaiter = mode;
    this.thread = thread;
}
//这是一双向链表,每个节点记录前一个节点与后一个节点
//Node节点中的值,是一个线程,相当于把等待的线程都以节点的形式加入到等待队列中
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;
}

方法返回后调用acquireQueued方法

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)) {//如果当前节点的前一个节点是头结点,那么尝试将当前线程使用CAS设置为独占线程
                setHead(node);//设置成功以将该节点设置为头结点
                p.next = null; // help GC   设置为null,告诉GC可以进行回收
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) &&//调用parkAndCheckInterrupt
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);//阻塞当前线程线程
    return Thread.interrupted();
}
//把当前线程阻塞,加入到阻塞队列中
public static void park(Object blocker) {
    Thread t = Thread.currentThread();
    setBlocker(t, blocker);
    UNSAFE.park(false, 0L);
    setBlocker(t, null);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!