Condition实现等待通知机制
提供类似 Object 的监视器方法,配合 Lock 可以实现等待/通知模式。
当前线程调用 Condition对象中的方法时,要先获取 Lock对象(即锁),再由 Lock 对象创建出来。
使用方法简单:在调用前要先获取锁。
Condition 对象是依赖 Lock 对象的。
一、接口分析
1、Lock
接口
java.util.concurrent.locks.Lock
public interface Lock {
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
void unlock();
/**
* Returns a new {@link Condition} instance that is bound to this
* {@code Lock} instance.
*
* <p>Before waiting on the condition the lock must be held by the
* current thread.
* A call to {@link Condition#await()} will atomically release the lock
* before waiting and re-acquire the lock before the wait returns.
*
* <p><b>Implementation Considerations</b>
*
* <p>The exact operation of the {@link Condition} instance depends on
* the {@code Lock} implementation and must be documented by that
* implementation.
*
* @return A new {@link Condition} instance for this {@code Lock} instance
* @throws UnsupportedOperationException if this {@code Lock}
* implementation does not support conditions
*/
Condition newCondition();
}
2、Condition
接口
java.util.concurrent.locks.Condition
public interface Condition {
void await() throws InterruptedException;
void awaitUninterruptibly();
long awaitNanos(long nanosTimeout) throws InterruptedException;
boolean await(long time, TimeUnit unit) throws InterruptedException;
boolean awaitUntil(Date deadline) throws InterruptedException;
void signal();
void signalAll();
}
二、Condition
实现分析
每个 Condition
对象都包含着一个等待队列,该队列是 Condition
对象实现等待/通知的关键。
下面将分析Condition
的实现:主要包括:等待队列、等待和通知。
Condition
接口的实现类是ConditionObject
,这个类是 AQS
里面的一个内部类。在这个实现中,维护这一个等待队列。
1、等待队列
等待队列是一个FIFO
的队列,队列中的每个节点 Node
,由上面的分子可知,每个 Node 里面都包含一个线程引用,该线程就是在 Condition
对象上等待的线程。
如果一个线程调用了Condition.await()
方法,那么该线程将会释放锁、构造节点加入等待队列并进入等待状态。
事实上,节点的定义复用了同步器中节点的定义,也就是说,同步队列和等待队列中节点类型都是同步器的静态内部类java.util.concurrent.locks.AbstractQueuedSynchronizer.Node
下面看下Condition
接口的实现类:
java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
/** First node of condition queue. */
private transient Node firstWaiter;// 等待队列的首节点
/** Last node of condition queue. */
private transient Node lastWaiter; // 等待队列的尾结点
/**
* Creates a new {@code ConditionObject} instance.
*/
public ConditionObject() {
}
// Internal methods
}
一个Condition
包含一个等待队列,Condition 拥有首节点和尾结点。当前线程调用await()方法,将会以当前线程构造节点,并将节点从尾部添加入等待队列。
2、等待
2.1 await()
调用了该方法,会使得当前线程进入等待队列,并释放锁,同时线程状态变为等待状态。
当从 await()方法返回时,当前线程一定获取了 Condition 相关的锁。
如果从队列(同步队列和等待队列)的角度看 await 方法的话,当调用 await()时,相当于同步队列的首节点(获取了锁的节点)移动了 Condition 的等待队列中。
java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject#await()
public final void await()