AQS

我们要知道AQS是JUC的基石

我们用ReentrantLock来举例

当线程进来后,直接利用CAS尝试抢占锁,如果抢占成功,则state被改成1,且设置对象独占锁线程为当前线程

protected final boolean compareAndSetState(int expect, int update) {
    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}

protected final void setExclusiveOwnerThread(Thread thread) {
    exclusiveOwnerThread = thread;
}

假设有有多个线程,A强到锁锁之后,

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

B进行判断 !tryAcquire(arg) 判断,其中的具体代码如下

final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {  //如果没有线程抢占锁
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {  //如果抢占锁的是自己
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

那么会执行 addWaiter() 方法进入队列,将B线程放入队列

private Node addWaiter(Node mode) {    
    Node node = new Node(Thread.currentThread(), mode);
    Node pred = tail;
    if (pred != null) {
        node.prev = pred;
        if (compareAndSetTail(pred, node)) {
            pred.next = node;
            return node;
        }
    }
    enq(node);
    return node;
}

其中注意看,如果B是队列中第一个线程,则会创建一个虚拟头节点,然后将B加在虚拟头节点后面。

然后尝试强锁,如果抢锁失败,则会将Node节点(前一个节点)的waitStatue改为-1,如果有第三个线程C入队,则跟B过程一样。其中底层会调用LockSupport.park()来让BC线程暂停在队列中

 

如果A已经完成,锁释放,然后查看node节点的waitStatue为-1,则会执行unparkSuccessor()来释放node的后置节点

 

以上是非公平锁,公平锁是基于非公平锁的基础上来实现的。

posted @ 2023-03-19 17:59  冬日寻雾记  阅读(18)  评论(0)    收藏  举报