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 {