ReentrantLock 和AQS

抽象队列同步器,通过一个int类型变量表示持有锁的状态。
state + FIFO队列(head、tail、node(waitStatus,Thread,prev,next))

AQS使用一个volatile的int 类型的成员变量来表示同步状态,通过内置的FIFO队列来完成资源获取的排队工作,将每条要去抢占资源的线程封装成一个node节点来实现锁的分配,通过CAS完成对state值的修改

Lock.lock()解析

// lock方法调用sync的lock,Sync extends AbstractQueuedSynchronizer
public void lock() {
        sync.lock();
    }
// 调用非公平锁的lock
static final class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;
    final void lock() {
    	// 先进行cas前瞻
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }
// 
}
// 核心代码
public final void acquire(int arg) {
    if (!tryAcquire(arg) && // 再次尝试获取锁和查看是否锁可重入,可以获取返回true
         acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) 
       	// addWaiter 添加node节点到队列中,第一次需要初始化队列,head指向空节点(哨兵)
       	// acquireQueued 如果prev指向head再次尝试获取锁,获取失败node的prev waitStatus设置-1,且		LockSupport.park(this); 等待唤醒(被unpark,中断),返回当前线程中断状态并清空中断状态,返回true。
         selfInterrupt();
    }
// 1 tryAcquire(arg)
protected final boolean tryAcquire(int acquires) {
    return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
   final Thread current = Thread.currentThread();
   // 获取 aqs state 状态
    int c = getState();
    // 0 直接cas 抢占锁
    if (c == 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;
}
// addWaiter(Node.EXCLUSIVE),添加node节点到队列中,第一次需要初始化队列,head指向空节点(哨兵)
private Node addWaiter(Node mode) {
    Node node = new Node(Thread.currentThread(), mode);
    // pred 尾指针指向的节点
    Node pred = tail;
    // 如果节点存在,直接cas把node节点加入进去队列,返回node节点
    if (pred != null) {
        node.prev = pred;
        if (compareAndSetTail(pred, node)) {
            pred.next = node;
            return node;
        }
    }
    // 初始化节点,再加入node
    enq(node);
    return node;
}

private Node enq(final Node node) {
    for (;;) {
        Node t = tail;
        // 初始化节点
        if (t == null) { // Must initialize
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
        	// 队列添加 node 节点
            node.prev = t;
            if (compareAndSetTail(t, node)) {
                t.next = node;
                return t;
            }
        }
    }
}

// acquireQueued
final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
    	// 中断标志
        boolean interrupted = false;
        for (;;) {
            final Node p = node.predecessor();
            // prev 是头指针,再次尝试获取锁
            if (p == head && tryAcquire(arg)) {
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            // 把node的前一个节点的waitStatus设置成-1
            if (shouldParkAfterFailedAcquire(p, node) &&
            	// LockSupport.park(this) 阻塞,等待被唤醒
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }
public void unlock() {
    sync.release(1);
}

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

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) {

    int ws = node.waitStatus;
    if (ws < 0)
        compareAndSetWaitStatus(node, ws, 0);

    Node s = node.next;
    if (s == null || s.waitStatus > 0) {
        s = null;
        //从队尾开始循环直到拿到离note最近的状态<0的节点
        for (Node t = tail; t != null && t != node; t = t.prev)
            if (t.waitStatus <= 0)
                s = t;
    }
    if (s != null)
        LockSupport.unpark(s.thread);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值