1. ReentrantLock
// 对象适配器模式
// Target:java.util.concurrent.locks.Lock
// Adapter:java.util.concurrent.locks.ReentrantLock
// Adaptee:java.util.concurrent.locks.Sync(NonfairSync/FairSync)对象
public class ReentrantLock implements Lock, java.io.Serializable {
private final Sync sync;
public ReentrantLock() {
sync = new NonfairSync(); // 非公平锁
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync(); // 公平锁 / 非公平锁
}
public void lock() {
sync.lock(); // Sync
}
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
public void unlock() {
sync.release(1);
}
protected Collection<Thread> getQueuedThreads() {
return sync.getQueuedThreads();
}
protected Collection<Thread> getWaitingThreads(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
}
... ...
}
2. ReentrantLock.Sync(FairSync/NonfairSync)
abstract static class Sync extends AbstractQueuedSynchronizer {
abstract void lock();
// 尝试非公平抢锁
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) { // 不进入SyncQueue排队,直接抢锁
setExclusiveOwnerThread(current); // 置当前线程为锁的独占者
return true; // 成功抢锁
}
}
else if (current == getExclusiveOwnerThread()) { // 当前线程已占有锁
// Reentrant
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc); // 更新锁状态(锁计数)
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;
}
// 新建条件变量
final ConditionObject newCondition() {
// ConditonObject为AbstractQueuedSynchronizer的非静态内部类
// ConditonObject对象将与当前Sync对象绑定
return new ConditionObject();
}
... ...
}
static final class NonfairSync extends Sync {
// 非公平抢锁
final void lock() {
if (compareAndSetState(0, 1)) // 不进入SyncQueue排队,直接抢锁
setExclusiveOwnerThread(Thread.currentThread()); // 置当前线程为锁的独占者
else // 抢锁失败
acquire(1); // tryAcquire失败,则进入SyncQueue排队等锁
}
// 尝试非公平抢锁
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
static final class FairSync extends Sync {
// 公平取锁
final void lock() {
acquire(1);// tryAcquire失败,则进入SyncQueue排队等锁
}
// 尝试公平取锁
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() && // SyncQueue为空 || SyncQueue中下个待唤醒线程为当前线程
compareAndSetState(0, acquires)) { // 可能失败:SyncQueue头结点中的线程正在同步运行,尚未释放锁
setExclusiveOwnerThread(current); // 置当前线程为锁的独占者
return true; // 成功取锁
}
}
else if (current == getExclusiveOwnerThread()) { // 当前线程已占有锁
// Reentrant
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc); // 更新锁状态(锁计数)
return true; // 已占有锁
}
return false; // 取锁失败
}
}
3. AbstractQueuedSynchronizer.Node
static final class Node {
static final Node SHARED = new Node();
static final Node EXCLUSIVE = null; // addWaiter
static final int CANCELLED = 1; // 取消等锁标记
static final int SIGNAL = -1; // unpark next节点标记
static final int CONDITION = -2; // ConditionQueue标记
static final int PROPAGATE = -3;
volatile int waitStatus; // 0、1、-1、-2、-3
volatile Node prev; // SyncQueue
volatile Node next; // SyncQueue
volatile Thread thread;
Node nextWaiter; // ConditionQueue
... ...
Node() { // 用于SyncQueue设置初始头结点
}
Node(Thread thread, Node mode) { // 用于AbstractQueuedSynchronizer.addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { // 用于ConditionObject.addConditionWaiter
this.waitStatus = waitStatus;
this.thread = thread;
}
}
4. AbstractQueuedSynchronizer
public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable {
protected AbstractQueuedSynchronizer() { }
private volatile int state; // 锁状态(锁计数)
// 获取锁状态
protected final int getState() {
return state;
}
// 设置锁状态
protected final void setState(int newState) {
state = newState;
}
// CAS设置锁状态
protected final boolean compareAndSetState(int expect, int update) {
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
// 尝试取锁,取锁失败则排队等锁
public final void acquire(int arg) {
if (!tryAcquire(arg) && // 尝试取锁
acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) // 排队等锁(独占锁:Node.EXCLUSIVE)
selfInterrupt(); // 排队过程中被中断,自我中断
}
private transient volatile Node head; // SyncQueue头节点(当前占有锁,且可能正在运行)
private transient volatile Node tail; // SyncQueue尾节点
// 设置头节点
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
// CAS设置head
private final boolean compareAndSetHead(Node update) {
return unsafe.compareAndSwapObject(this, headOffset, null, update);
}
// CAS设置tail
private final boolean compareAndSetTail(Node expect, Node update) {
return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
}
// 在SyncQueue末尾添加节点
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode); // 创建等待节点
Node pred = tail; /*记录tail*/
if (pred != null) { // SyncQueue不为空
node.prev = pred;// 可能其它线程正在同步设置tail,如:
// A、B线程tryAcquire失败,同步在SyncQueue末尾添加节点
if (compareAndSetTail(pred, node)) { /*CAS设置tail = node*/
// CAS(tail)成功
pred.next = node;
return node;
}
}
// tail为空 || CAS(tail)失败
enq(node);
return node;
}
// 在SyncQueue末尾添加节点(直到成功)
private Node enq(final Node node) {
for (;;) {
// CAS(head || tail)失败将回到此处
Node t = tail; /*记录tail*/
if (t == null) { // SyncQueue为空
// 可能其它线程正在同步设置head,如:
// A、B线程tryAcquire失败,同步在SyncQueue中添加首个节点
if (compareAndSetHead(new Node())) /*CAS设置head = new Node()*/
// CAS(head)成功
tail = head;
} else { // SyncQueue不为空
node.prev = t; // node.prev = tail
// 可能其它线程正在同步设置tail,如:
// A、B线程tryAcquire失败,同步在SyncQueue末尾添加节点
if (compareAndSetTail(t, node)) { /*CAS设置tail = node*/
// CAS(tail)成功
t.next = node; // tail.next = node
return t;
}
}
}
}
// 排队等锁
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor(); // node.prev// tryAcquire可能失败:head正在运行,尚未释放锁 || 其它线程非公平抢锁
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false; // 取锁成功
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) && // tryAcquire失败后是否park当前线程
parkAndCheckInterrupt()) // park当前线程,unpark后检查中断
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node); // node取消排队
}
}
// tryAcquire失败后是否park当前线程
// 为何node节点在park前必须确保pred.waitStatus = Node.SIGNAL,详见doReleaseShared(ReadWriteLock)
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus; /*记录pred.waitStatus*/
if (ws == Node.SIGNAL)
return true;
if (ws > 0) { // pred.waitStatus > 0:pred取消排队,pred无法唤醒node
// 寻找前置位首个未取消排队的节点,同时清理取消排队的节点
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else { // pred.waitStatus <= 0:pred在排队,pred能唤醒node
// 可能pred已取消排队,正在cancelAcquire中同步设置pred.waitStatus = Node.CANCELLED
// 可能pred为SyncQueue头结点,正在doReleaseShared中同步设置pred.waitStatus = Node.PROPAGATE
compareAndSetWaitStatus(pred, ws, Node.SIGNAL); /*CAS设置pred.waitStatus = Node.SIGNAL*/
}
return false;
}
// park当前线程,park return后检查中断
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this); // park当前线程
return Thread.interrupted(); // 检查中断
}
// node取消排队(超时 || 被中断)
private void cancelAcquire(Node node) {
if (node == null)
return;
node.thread = null;// 寻找前置位首个未取消排队的节点pred
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
Node predNext = pred.next; /*记录pred.next*/
node.waitStatus = Node.CANCELLED;// node为末尾节点,即node后置位没有其它节点
// 可能其它线程正在SyncQueue末尾添加节点(请参考addWaiter、enq)
if (node == tail && compareAndSetTail(node, pred)) { // node == tail ? CAS设置tail = pred
// CAS(tail)成功
// 可能其它线程已在SyncQueue末尾添加新节点:CAS(pred.next)将失败
compareAndSetNext(pred, predNext, null); /*CAS设置pred.next = null*/
} else { // node非末尾节点 || CAS(tail)失败
int ws;
if (pred != head && pred.thread != null && // pred不为head && pred尚未执行
((ws = pred.waitStatus) == Node.SIGNAL || /*记录pred.waitStatus*/
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL)))) { /*CAS设置pred.waitStatus = Node.SIGNAL*/
// 可能pred已成为head,但pred能unpark node后置位排队的节点
// 可能pred正在(或已经)取消排队(影响不大)
Node next = node.next;
if (next != null && next.waitStatus <= 0) // node.next存在且未取消排队
// pred - X - Y - Z - :X、Y、Z同步取消排队
// 同步结果:pred.next = Z.next
compareAndSetNext(pred, predNext, next); /*CAS设置pred.next = node.next*/
} else { // pred为head || pred取消排队 || CAS(pred.waitStatus)失败
// 1. pred为head:head正在(或已经)unpark node || head = new Node,无法唤醒后置位排队的节点
// 2. pred取消排队 || CAS(pred.waitStatus)失败(影响不大)
// pred取消排队:若pred前置位首个未取消排队的节点为head,则pred将立刻唤醒后置位排队的节点
unparkSuccessor(node); // 立刻唤醒node后置位首个排队等锁的节点
}
node.next = node; //help GC
}
}
// 自我中断
static void selfInterrupt() {
Thread.currentThread().interrupt();
}
// 尝试释放锁,成功释放锁时unpark successor
public final boolean release(int arg) {
if (tryRelease(arg)) { // 尝试释放锁
// 成功释放锁
// 此时state = 0,exclusiveOwnerThread = null
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h); // unpark head后置位首个未取消排队的节点
return true;
}
// 未释放锁
return false;
}
// 唤醒node后置位首个未取消排队的节点
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已取消等锁
s = null; // node后置位首个未取消排队的节点
for (Node t = tail; t != null && t != node; t = t.prev) // 从SyncQueue尾部向前遍历
if (t.waitStatus <= 0) // 未取消等锁
s = t; // 记录t
}
if (s != null)
LockSupport.unpark(s.thread); // 唤醒线程
}
// 完全释放锁
final int fullyRelease(Node node) {
boolean failed = true;
try {
int savedState = getState(); // 获取锁计数
if (release(savedState)) {
// 成功释放锁
failed = false;
return savedState; // return 锁释放前的状态
} else {
// 未释放锁
throw new IllegalMonitorStateException(); // 立刻抛出异常
}
} finally {
if (failed) // 释放锁失败
node.waitStatus = Node.CANCELLED; // 标记node为取消排队节点
}
}
// 尝试取锁,取锁失败则排队等锁(可被中断)
public final void acquireInterruptibly(int arg) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))
doAcquireInterruptibly(arg);
}
// 排队等锁(可被中断)
private void doAcquireInterruptibly(int arg) throws InterruptedException {
final Node node = addWaiter(Node.EXCLUSIVE);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException(); // 立即抛出InterruptedException
}
} finally {
if (failed) // 被中断
cancelAcquire(node); // node取消排队
}
}
// 尝试取锁,取锁失败则排队等锁(nanosTimeout时间内)
public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquire(arg) ||
doAcquireNanos(arg, nanosTimeout);
}
static final long spinForTimeoutThreshold = 1000L; // 1000ns内:no park just spin
// 排队等锁(nanosTimeout时间内)
private boolean doAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {
if (nanosTimeout <= 0L)
return false;
final long deadline = System.nanoTime() + nanosTimeout; // 计算deadline
final Node node = addWaiter(Node.EXCLUSIVE);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return true;
}
nanosTimeout = deadline - System.nanoTime(); // 计算nanosTimeout
if (nanosTimeout <= 0L) // 超时
return false;
if (shouldParkAfterFailedAcquire(p, node) &&
nanosTimeout > spinForTimeoutThreshold) // nanosTimeout > 1000ns
LockSupport.parkNanos(this, nanosTimeout);// park当前线程
if (Thread.interrupted())
throw new InterruptedException();// 立即抛出InterruptedException
}
} finally {
if (failed) // 被中断 || 超时
cancelAcquire(node);// 取消排队
}
}
// SyncQueue不为空 && SyncQueue中下个待唤醒节点非当前线程所在节点
public final boolean hasQueuedPredecessors() {
Node t = tail; // 记录tail
Node h = head; // 记录head
Node s;
return h != t && // SyncQueue不为空
((s = h.next) == null || // head不存在后置节点
s.thread != Thread.currentThread()); // head.next.thread != 当前线程
}
// 获取所有在SyncQueue中排队的线程
public final Collection<Thread> getQueuedThreads() {
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node p = tail; p != null; p = p.prev) { // 从SyncQueue尾部向前遍历(具体原因请参考cancelAcquire方法)
Thread t = p.thread;
if (t != null) // p未占有锁 && p未取消排队
list.add(t);
}
return list;
}
// node从ConditionQueue转移至SyncQueue(node被signal唤醒)
final boolean transferForSignal(Node node) {
// 可能其它线程正在同步设置node.status,如:
// A线程正在signal(node),此时B线程由于被中断 || await超时,同步cancel(node)
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))// CAS(node.waitStatus)失败:node被中断 || await超时后,node被signal
return false;
Node p = enq(node); // node进入SyncQueue
int ws = p.waitStatus;
// A线程正在signal(node),此时B线程由于被中断 || await超时,同步cancel(node)
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))// p已取消排队 || CAS(p.waitStatus)失败
LockSupport.unpark(node.thread);
return true;
}
// node从ConditionQueue转移至SyncQueue(node取消等待:被中断 || await超时)
final boolean transferAfterCancelledWait(Node node) {
// 可能其它线程正在同步设置node.status,如:
// A线程正在cancel(node),此时B线程在满足特定条件时同步signal(node)
if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
enq(node); // node进入SyncQueue
return true;
}
// CAS(node.waitStatus)失败:node被中断 || await超时前,node被signal
while (!isOnSyncQueue(node)) // 等待node进入SyncQueue
Thread.yield();
return false;
}
// node是否位于SyncQueue
final boolean isOnSyncQueue(Node node) {
// 一定不在SyncQueue
if (node.waitStatus == Node.CONDITION || node.prev == null)
return false;
// 一定在SyncQueue
if (node.next != null)
return true;
return findNodeFromTail(node); // 从SyncQueue尾部向前查找node
}
// 从SyncQueue尾部向前查找node
private boolean findNodeFromTail(Node node) {
Node t = tail;
for (;;) {
if (t == node)
return true;
if (t == null)
return false;
t = t.prev;
}
}
// 获取所有在condition上等待的线程
public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
if (!owns(condition))
throw new IllegalArgumentException("Not owner");
return condition.getWaitingThreads();
}
... ...
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long stateOffset;
private static final long headOffset;
private static final long tailOffset;
private static final long waitStatusOffset;
private static final long nextOffset;
static {
try {
stateOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("state"));
headOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("head"));
tailOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
waitStatusOffset = unsafe.objectFieldOffset(Node.class.getDeclaredField("waitStatus"));
nextOffset = unsafe.objectFieldOffset(Node.class.getDeclaredField("next"));
} catch (Exception ex) { throw new Error(ex); }
}
private static final boolean compareAndSetWaitStatus(Node node, int expect, int update) {
return unsafe.compareAndSwapInt(node, waitStatusOffset, expect, update);
}
private static final boolean compareAndSetNext(Node node, Node expect, Node update) {
return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
}
}
5. AbstractQueuedSynchronizer.ConditionObject
// 当前线程已拥有锁,ConditionObject中的方法无需同步(不存在CAS操作)
public class ConditionObject implements Condition, java.io.Serializable {
private transient Node firstWaiter; // ConditionQueue头结点
private transient Node lastWaiter; // ConditionQueue尾节点
public ConditionObject() {}
// 在Condition上等待
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter(); // 在ConditionQueue中添加节点
int savedState = fullyRelease(node);
int interruptMode = 0;
// node进入SyncQueue:被signal、被中断、await超时
while (!isOnSyncQueue(node)) {
LockSupport.park(this); // park当前线程
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) //检查中断,return interruptMode
break;// 存在中断时break
}
// 进入SyncQueue排队等锁
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters(); // 移除ConditionQueue中所有已进入SyncQueue的节点
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode); // 依interruptMode处理中断
}
// 在ConditionQueue中添加节点
private Node addConditionWaiter() {
Node t = lastWaiter;
if (t != null && t.waitStatus != Node.CONDITION) {
unlinkCancelledWaiters(); // 移除ConditionQueue中所有已进入SyncQueue的节点
t = lastWaiter;
}
// 添加新节点到ConditionQueue尾部
Node node = new Node(Thread.currentThread(), Node.CONDITION);
if (t == null)
firstWaiter = node;
else
t.nextWaiter = node;
lastWaiter = node;
return node;
}
// 移除ConditionQueue中所有已进入SyncQueue的节点
private void unlinkCancelledWaiters() {
Node t = firstWaiter;
Node trail = null;
while (t != null) { // 遍历ConditionQueue,t为当前节点
Node next = t.nextWaiter;
if (t.waitStatus != Node.CONDITION) { // 移除t
t.nextWaiter = null;
if (trail == null)
firstWaiter = next;
else
trail.nextWaiter = next;
if (next == null)
lastWaiter = trail;
}
else
trail = t;
t = next;
}
}
private static final int REINTERRUPT = 1;
private static final int THROW_IE = -1;
//检查中断,return interruptMode
private int checkInterruptWhileWaiting(Node node) {
// signal前被中断:interruptMode = THROW_IE
// signal后被中断:interruptMode = REINTERRUPT
return Thread.interrupted() ? (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : 0;
}
// 依interruptMode处理中断
private void reportInterruptAfterWait(int interruptMode) throws InterruptedException {
if (interruptMode == THROW_IE)
throw new InterruptedException();
else if (interruptMode == REINTERRUPT)
selfInterrupt();
}
// 将在ConditionQueue中等待的首个节点转移至SyncQueue
public final void signal() {
if (!isHeldExclusively()) // 当前线程是否为锁的独占者
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignal(first);
}
// 将在ConditionQueue中等待的首个节点转移至SyncQueue
private void doSignal(Node first) {
do {
if ((firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null; // 置nextWaiter为空
} while (!transferForSignal(first) && (first = firstWaiter) != null);
}
// 将在ConditionQueue中等待的所有节点转移至SyncQueue
public final void signalAll() {
if (!isHeldExclusively()) // 当前线程是否为锁的独占者
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignalAll(first);
}
// 将在ConditionQueue中等待的所有节点转移至SyncQueue
private void doSignalAll(Node first) {
lastWaiter = firstWaiter = null;
do {
Node next = first.nextWaiter;
first.nextWaiter = null; // 置nextWaiter为空
transferForSignal(first);// node从ConditionQueue转移至SyncQueue
first = next;
} while (first != null); // 遍历ConditionQueue,当前节点为first
}
// 在Condition上等待(不可被中断,不调用checkeInterruptWhileWaiting)
public final void awaitUninterruptibly() {
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean interrupted = false;
while (!isOnSyncQueue(node)) { // node进入SyncQueue前等待
LockSupport.park(this);
if (Thread.interrupted()) // 检查中断
interrupted = true; // 记录中断状态,继续等待signal
}
// 进入SyncQueue排队等锁
if (acquireQueued(node, savedState) || interrupted)
selfInterrupt(); // 自我中断
}
// 在Condition上等待(nanosTimeout时间内)
public final long awaitNanos(long nanosTimeout) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
final long deadline = System.nanoTime() + nanosTimeout; // 计算deadline
int interruptMode = 0;
while (!isOnSyncQueue(node)) { // node进入SyncQueue前等待
if (nanosTimeout <= 0L) {
transferAfterCancelledWait(node); // 超时
break;
}
if (nanosTimeout >= spinForTimeoutThreshold) // 剩余时间 >= 1000纳秒
LockSupport.parkNanos(this, nanosTimeout);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) //检查中断
break;// 存在中断时break
nanosTimeout = deadline - System.nanoTime(); // 计算剩余时间
}
// 进入SyncQueue排队等锁
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters(); // 移除ConditionQueue中所有已进入SyncQueue的节点
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode); // 处理中断
return deadline - System.nanoTime();
}
public final boolean await(long time, TimeUnit unit) throws InterruptedException;
// 获取所有在ConditionQueue上等待的节点(线程)
protected final Collection<Thread> getWaitingThreads() {
if (!isHeldExclusively()) // 当前线程是否为锁的独占者
throw new IllegalMonitorStateException();
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node w = firstWaiter; w != null; w = w.nextWaiter) { // 遍历ConditionQueue,w为当前节点
if (w.waitStatus == Node.CONDITION) { // w未进入SyncQueue
Thread t = w.thread;
if (t != null)
list.add(t);
}
}
return list;
}
... ...
}