一、Condition接口
public interface Condition {
/**
* 暂停此线程直至一下四种情况发生
* 1.此Condition被signal()
* 2.此Condition被signalAll()
* 3.Thread.interrupt()
* 4.伪wakeup
* 以上情况.在能恢复方法执行时,当前线程必须要能获得锁
*/
void await() throws InterruptedException;
//跟上面类似,不过不响应中断
void awaitUninterruptibly();
//带超时时间的await()
long awaitNanos(long nanosTimeout) throws InterruptedException;
//带超时时间的await()
boolean await(long time, TimeUnit unit) throws InterruptedException;
//带deadline的await()
boolean awaitUntil(Date deadline) throws InterruptedException;
//唤醒某个等待在此condition的线程
void signal();
//唤醒所有等待在此condition的所有线程
void signalAll();
}
二、ConditionObject解析
/**
* ConditionObject的实现,其实其维护两个队列
* 1)Condition队列,表示等待的队列,其waitStatus=Node.CONDITION,由firstWaiter和lastWaiter两个属性操控.
* 2)Sync队列,表示可以竞争锁的队列,这个跟AQS一致,waitStatus=0;
* 3)await()把当前线程创建一个Node加入Condition队列,接着就一直循环查其在不在Sync队列
* 如果当前节点在Sync队列里了,就可以竞争锁,恢复运行了.
* 4)signal()方法就是把某个节点的nextWaiter设为null,再把其从Condition队列转到Sync队列
*/
public class ConditionObject implements Condition, java.io.Serializable {
//condition队列的第一个节点
private transient Node firstWaiter;
//condition队列的最后一个节点
private transient Node lastWaiter;
public ConditionObject() { }
/**
* 往condition队列中添加新元素
*/
private Node addConditionWaiter() {
Node t = lastWaiter;
// If lastWaiter is cancelled, clean out.
if (t != null && t.waitStatus != Node.CONDITION) {
unlinkCancelledWaiters();//遍历condition队列,移除其中非CONDITION状态的元素
//lastWaiter非CONDITION状态,上一步遍历清除时lastWaiter发生了变化需要重新赋值
t = lastWaiter;
}
//新建一个CONDITION状态的节点,并将其加在condition队列尾部
Node node = new Node(Node.CONDITION);
if (t == null)//lastWaiter为null
firstWaiter = node;//firstWaiter指向新的node
else
t.nextWaiter = node;//lastWaiter不为null,node拼在lastWaiter后面
lastWaiter = node;//lastWaiter指向新增加在末尾的元素
return node;//返回新增元素
}
/**
* 暂停此线程,直至进入SyncQueue
* 线程唤醒时如果还是不在SyncQueue,会继续park
*/
public final void awaitUninterruptibly() {
Node node = addConditionWaiter();//往condition队列中添加新元素
int savedState = fullyRelease(node);//释放当前线程的锁
boolean interrupted = false;
while (!isOnSyncQueue(node)) {//node节点不在SyncQueue,就一直循环
LockSupport.park(this);//阻塞node的线程
//线程唤醒时,继续循环,如果还是不在SyncQueue,继续park休眠
if (Thread.interrupted())
interrupted = true;
}
//跳出来,说明线程进入SyncQueue了,acquireQueued作用:阻塞node
if (acquireQueued(node, savedState) || interrupted)
selfInterrupt();//中断线程
}
/**
* 释放信号
*/
public final void signal() {
if (!isHeldExclusively())//不是独占模式(排它模式)抛出异常
throw new IllegalMonitorStateException();
//将等待队列的第一个节点出队列,并将其加入AQS的锁队列
Node first = firstWaiter;
if (first != null)
doSignal(first);
}
/**
* Removes and transfers nodes until hit non-cancelled one or
* null. Split out from signal in part to encourage compilers
* to inline the case of no waiters.
* @param first (non-null) the first node on condition queue
*/
private void doSignal(Node first) {
do {
if ((firstWaiter = first.nextWaiter) == null)//第一个元素空了,说明condition队列空了
lastWaiter = null;//最后一个元素引用置空
//将first.nextWaiter置空,也就是从condition队列中出列
first.nextWaiter = null;
//如果转换队列不成功且condition队列不为null,继续循环
} while (!transferForSignal(first) && (first = firstWaiter) != null);
}
/**
* 唤醒所有等待在此condition的所有线程
*/
public final void signalAll() {
if (!isHeldExclusively())//非独占模式,抛出异常
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignalAll(first);
}
/**
* 唤醒所有等待在此condition的所有线程
*/
private void doSignalAll(Node first) {
lastWaiter = firstWaiter = null;
do {//循环遍历condition队列,一个个塞到Sync队列中
Node next = first.nextWaiter;
first.nextWaiter = null;
transferForSignal(first);
first = next;
} while (first != null);
}
/**
* 遍历condition队列,移除其中非CONDITION状态的元素
*/
private void unlinkCancelledWaiters() {
Node t = firstWaiter;
Node trail = null;
while (t != null) {//遍历condition队列
Node next = t.nextWaiter;
if (t.waitStatus != Node.CONDITION) {
t.nextWaiter = null;//这样t就从condition中移除了
if (trail == null)
firstWaiter = next;//指向下一个元素,再次遍历
else//trail是上一个元素且为CONDITION状态
trail.nextWaiter = next;//上一个元素与本元素的下一个元素相连,本元素被剔除
if (next == null)
lastWaiter = trail;//没有下一个元素了,lastWaiter指向trail
} else {
trail = t;
}
t = next;
}
}
...
/**
* 参考上面对awaitUninterruptibly(..)的分析
*/
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int 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);
}
/**
* 参考上面对awaitUninterruptibly(..)的分析
*/
public final long awaitNanos(long nanosTimeout) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
// We don't check for nanosTimeout <= 0L here, to allow
// awaitNanos(0) as a way to "yield the lock".
final long deadline = System.nanoTime() + nanosTimeout;
long initialNanos = nanosTimeout;
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (nanosTimeout <= 0L) {
transferAfterCancelledWait(node);
break;
}
if (nanosTimeout > SPIN_FOR_TIMEOUT_THRESHOLD)
LockSupport.parkNanos(this, nanosTimeout);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
nanosTimeout = deadline - System.nanoTime();
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
long remaining = deadline - System.nanoTime(); // avoid overflow
return (remaining <= initialNanos) ? remaining : Long.MIN_VALUE;
}
/**
* 参考上面对awaitUninterruptibly(..)的分析
*/
public final boolean awaitUntil(Date deadline) throws InterruptedException {
long abstime = deadline.getTime();
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean timedout = false;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (System.currentTimeMillis() >= abstime) {
timedout = transferAfterCancelledWait(node);
break;
}
LockSupport.parkUntil(this, abstime);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
return !timedout;
}
/**
* 参考上面对awaitUninterruptibly(..)的分析
*/
public final boolean await(long time, TimeUnit unit)
throws InterruptedException {
long nanosTimeout = unit.toNanos(time);
if (Thread.interrupted())
throw new InterruptedException();
// We don't check for nanosTimeout <= 0L here, to allow
// await(0, unit) as a way to "yield the lock".
final long deadline = System.nanoTime() + nanosTimeout;
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean timedout = false;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (nanosTimeout <= 0L) {
timedout = transferAfterCancelledWait(node);
break;
}
if (nanosTimeout > SPIN_FOR_TIMEOUT_THRESHOLD)
LockSupport.parkNanos(this, nanosTimeout);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
nanosTimeout = deadline - System.nanoTime();
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
return !timedout;
}
...
/**
* 获取condition队列中所有等待的线程并返回
*/
protected final Collection<Thread> getWaitingThreads() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
ArrayList<Thread> list = new ArrayList<>();
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
if (w.waitStatus == Node.CONDITION) {
Thread t = w.thread;
if (t != null)
list.add(t);
}
}
return list;
}
}