All Known Implementing Classes:
AbstractQueuedLongSynchronizer.ConditionObject, AbstractQueuedSynchronizer.ConditionObject
All Methods Instance Methods Abstract Methods Modifier and TypeMethod and Descriptionvoidawait()Causes the current thread to wait until it is signalled or interrupted.
使当前线程等待,直到发出信号或中断。
booleanawait(long time, TimeUnit unit)Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.
使当前线程等待,直到发出信号或中断,或指定的等待时间过去。
longawaitNanos(long nanosTimeout)Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.
使当前线程等待,直到发出信号或中断,或指定的等待时间过去。
voidawaitUninterruptibly()Causes the current thread to wait until it is signalled.
使当前线程等待,直到发出信号
booleanawaitUntil(Date deadline)Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses.
使当前线程等待,直到发出信号或中断,或指定的截止时间过去。
voidsignal()Wakes up one waiting thread.
唤醒一个等待的线程(如果有任何线程正在等待此条件,则选择一个线程进行唤醒。然后,该线程必须在从await返回之前重新获取锁。)
voidsignalAll()Wakes up all waiting threads.
唤醒所有等待的线程
Condition是在java 1.5中才出现的,它用来替代传统的Object的wait()、notify()实现线程间的协作,相比使用Object的wait()、notify(),使用Condition的await()、signal()这种方式实现线程间协作更加安全和高效。因此通常来说比较推荐使用Condition,阻塞队列实际上是使用了Condition来模拟线程间协作。 Condition是个接口,基本的方法就是await()和signal()方法; Condition依赖于Lock接口,生成一个Condition的基本代码是lock.newCondition() 调用Condition的await()和signal()方法,都必须在lock保护之内,就是说必须在lock.lock()和lock.unlock之间才可以使用 Conditon中的await()对应Object的wait(); Condition中的signal()对应Object的notify(); Condition中的signalAll()对应Object的notifyAll()。
使用示例
运行结果