AQS实现原理 (2)

acquireQueued()会先判断当前传入的Node对应的前置节点是否为head,如果是则尝试加锁。加锁成功则将当前节点设置为head节点,然后删除之前的head节点。

如果加锁失败或者Node的前置节点不是head节点,就会通过shouldParkAfterFailedAcquire方法将head节点的waitStatus变成SIGNAL=-1,最后执行parkAndChecknIterrupt方法,调用LockSupport.park()挂起当前线程。此时线程二需要等待其他线程释放锁来唤醒。

线程释放实现

线程一执行完后释放锁,具体代码如下:

java.util.concurrent.locks.AbstractQueuedSynchronizer.release():

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

先执行tryRelease方法,如果执行成功,则继续判断head节点的waitStatus是否为0,这个值为SIGNAL=-1不为0,继续执行unparkSuccessor()方法唤醒head的后置节点。

ReentrantLock.tryRelease():

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

执行完ReentrantLock.tryRelease()后,state被设置为0,Lock对象的独占锁被设置为null。

接着执行java.util.concurrent.locks.AbstractQueuedSynchronizer.unparkSuccessor()方法,唤醒head的后置节点:

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; for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread); }

这里主要是将head节点的waitStatus设置为0,然后解除head节点next的指向,使head几点空置,等待被垃圾回收。

此时重新将head指针指向线程二对应的Node节点,且使用LockSupport.unpark方法来唤醒线程二。被唤醒的线程会接着尝试获取锁,用CAS指令修改state数据。执行完成后AQS中的数据结构如下:

AQS实现原理

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgysgf.html