AQS-ConditionObject 笔记

ConditionObject

属性 说明
Node firstWaiter 头节点
Node lastWaiter 尾节点

为Condition接口实现,Condition的目的主要是替代Object的wait,notify,notifyAll方法的,它是基于Lock实现的.(而Lock是来替代synchronized方法).

结构

AQS-ConditionObject 笔记

使用时序图

AQS-ConditionObject 笔记


关键方法

阻塞线程:await

对应Object.wait(),通过AQS机制释放锁定的资源,终止当前线程,恢复后使用AQS独占模式重新锁定资源

acquireQueued:此时node节点已转换为AQS中节点

public final void await() throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    Node node = addConditionWaiter();
    long savedState = fullyRelease(node);
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
        LockSupport.park(this);
        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
            break;
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
        interruptMode = REINTERRUPT;
    if (node.nextWaiter != null) // clean up if cancelled
        unlinkCancelledWaiters();
    if (interruptMode != 0)
        reportInterruptAfterWait(interruptMode);
}

AQS-ConditionObject 笔记

唤醒线程:signal

transferForSignal转换节点后await()中acquireQueued(node,savedState)操作的节点已是AQS中的节点

isHeldExclusively:子类实现.判断是否独家持有

public final void signal() {
    if (!isHeldExclusively())
        throw new IllegalMonitorStateException();
    Node first = firstWaiter;
    if (first != null)
        doSignal(first);
}

AQS-ConditionObject 笔记

上一篇:java-Thread笔记


下一篇:Mars3D开发基础学习:Material材质