J.U.C多线程核心之AQS

341 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情

这里使用Reentrantlock带大家了解AQS线程工具类

重入锁ReentrantLock的初步认识

啥是锁?

锁是用来解决多线程并发访问个烘箱资源所带来的数据安全性问题的手段。 对一个共享资源加锁之后,如果有一个线程获得了锁,name其他线程无法访问这个共享资源。

啥是可重入锁?

一个持有锁的线程,在释放锁之前,如果再次访问加了该同步锁的其他方法,这个线程不需要再次争抢锁,只需要记录重入次数。

例子:

image-20220925150758431

锁的类图

image-20220925150914440

AQS是什么

我们先看类的关系:

ReentrantLock的关系类图

image.png

例子

用到上面一节的例子:

package JUC;
​
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
​
/**
 * @Author: sc
 * @Date: 2022/10/27 17:02
 */
public class AQSDemo {
​
    static Lock lock = new ReentrantLock();
    public static int count = 0;
    public static void incr(){
        try{
            lock.lock();
            Thread.sleep(1);
            count++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public static void decr(){
        lock.lock();
        count--;
        lock.unlock();
    }
​
    public static void main(String[] args) throws InterruptedException {
        for(int i = 0;i<1000;i++){
            new Thread(AQSDemo::incr).start();
        }
        Thread.sleep(4000);
        System.out.println("result:"+count);
    }
​
}

我们来看lock

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

lock有两个实现类:(ctrl+alt+click查看实现类)

image-20221027171853070

公平锁和非公平锁我就不介绍了(是否根据排队的顺序)

我们点到Reentrantlock里面可以看到里面是非公平锁

public ReentrantLock() {
    sync = new NonfairSync();
}

我们根据实现类找到他的非公平锁的lock的实现:

static final class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;
​
    /**
     * Performs lock.  Try immediate barge, backing up to normal
     * acquire on failure.
     */
    @ReservedStackAccess
    final void lock() {
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }
​
    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

cas修改state的值

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

你要互斥肯定需要一个共享资源,state(stateOffset)就是这个共享资源,它是AQS工具类里的一个成员变量

/**
 * The synchronization state.
 */
private volatile int state; // 0没锁  大于1有锁

只是改了一个参数就行了!优雅

如果上面的cas函数返回true, 然后再使用一个独占线程的方法,将他独占

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

这时候,来了线程B、C怎么办呢?然后还有else里的方法acquire

@ReservedStackAccess
final void lock() {
    if (compareAndSetState(0, 1))
        setExclusiveOwnerThread(Thread.currentThread());
    else
        acquire(1);
}
@ReservedStackAccess
public final void acquire(int arg) {
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

尝试去获取锁

protected final boolean tryAcquire(int acquires) {
    return nonfairTryAcquire(acquires);
}
@ReservedStackAccess
final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {// 获取state发现为0,说明无锁,直接占用
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {// 是不是重入状态
        int nextc = c + acquires;// 只要记录重入次数
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

addWaitter方法,实质上是构建了一个双向链表

这里可以画个图清楚一些:

image-20221027162425252

构建节点(排队)

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;
}

阻塞:

@ReservedStackAccess
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)) { // 死循环  tryAcquire尝试去获取节点
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) &&// 如果获取失败的话就阻塞
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
    int ws = pred.waitStatus;
    if (ws == Node.SIGNAL)
        /*
         * This node has already set status asking a release
         * to signal it, so it can safely park.
         */
        return true;
    if (ws > 0) {
        /*
         * Predecessor was cancelled. Skip over predecessors and
         * indicate retry.
         */
        do {
            node.prev = pred = pred.prev;
        } while (pred.waitStatus > 0);
        pred.next = node;
    } else {
        /*
         * waitStatus must be 0 or PROPAGATE.  Indicate that we
         * need a signal, but don't park yet.  Caller will need to
         * retry to make sure it cannot acquire before parking.
         */
        compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
    }
    return false;
}
private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this); // 线程B、C会被阻塞在这个位置    (unpark接触阻塞)
    return Thread.interrupted();
}

唤醒:

AQSunpark方法

现在我们来看unlock

唤醒阻塞的线程

public void unlock() {
    sync.release(1);
}
@ReservedStackAccess
public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}
@ReservedStackAccess
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);
}

B就消失了

image-20221027165012264