一、概述
AbstractQueuedSynchronizer (简称AQS)
AQS是一个用于构建锁和同步容器的框架。事实上concurrent包内许多类都是基于AQS构建,例如ReentrantLock,Semaphore,CountDownLatch,ReentrantReadWriteLock,FutureTask等。AQS解决了在实现同步容器时设计的大量细节问题
AQS使用一个FIFO的队列表示排队等待锁的线程,队列头节点称作“哨兵节点”或者“哑节点”,它不与任何线程关联。其他的节点与等待线程关联,每个节点维护一个等待状态waitStatus
二、源码
private transient volatile Node head; private transient volatile Node tail; private volatile int state; static final class Node { static final Node SHARED = new Node(); static final Node EXCLUSIVE = null; /** waitStatus value to indicate thread has cancelled */ static final int CANCELLED = 1; /** waitStatus value to indicate successor‘s thread needs unparking */ static final int SIGNAL = -1; /** waitStatus value to indicate thread is waiting on condition */ static final int CONDITION = -2; /** * waitStatus value to indicate the next acquireShared should * unconditionally propagate */ static final int PROPAGATE = -3; //取值为 CANCELLED, SIGNAL, CONDITION, PROPAGATE 之一 volatile int waitStatus; volatile Node prev; volatile Node next; // Link to next node waiting on condition, // or the special value SHARED volatile Thread thread; Node nextWaiter; }
示意图
013-AbstractQueuedSynchronizer-用于构建锁和同步容器的框架
原文:https://www.cnblogs.com/bjlhx/p/10365620.html