Condition 条件
一、Condition接口
如果和Object对象的wait()方法以及notify()方法对比,Condition就比较好理解了。Condition的主要方法作用和wait()以及notify()大致相同。主要区别点在于对象的wait()和notify()方法要和synchronized关键字组合使用,而Condition的方法主要和重入锁相关联。
在Lock接口中,有一个newCondition()方法用以生成与该锁绑定的一个Condition对象,利用这个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 接口定义的源码,方法的含义如下:
1、await()方法会使当前线程等待,同时释放锁,当其他线程中使用signal()或者signalAll()方法时,线程会重新获得锁并继续执行。或者当线程被中断时,也能跳出等待。有时间参数则超时会返回,返回前也会获得锁。
2、awaitUninterruptibly()方法作用和await()方法类似,但不会响应中断。
3、signal()方法用于唤醒一个在等待中的线程,signalAll()方法则是唤醒所有在等待中的线程。
二、JDK中Condition使用案例
Condition在JDK中使用比较多,根据ArrayBlockingQueue的put()和take()方法可以了解Condition的使用。
首先是一些关键的属性定义:
final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
// 构造方法中
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
下面是put方法:
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly(); // 加锁
try {

本文详细介绍了Java中的Condition接口,作为锁的一部分,它提供了比Object.wait()和notify()更强大的线程间协作能力。Condition允许线程在满足特定条件时等待,而其他线程可以在合适时机唤醒它们。在JDK中,Condition常用于 РеentrantLock 的实现,通过Condition对象,线程可以在加锁和解锁之间进行等待和唤醒操作。文章还探讨了AQS(AbstractQueuedSynchronizer)中Condition的实现,包括await()、signal()和signalAll()方法的工作原理,以及它们如何影响线程在条件队列和同步队列之间的转换。
最低0.47元/天 解锁文章
487

被折叠的 条评论
为什么被折叠?



