Condition作用和Object.wait()和Object.notify()方法作用类似,但是wait()和notify()是和synchronized关键字结合使用的,而Condition是和ReentrantLock(重入锁)相关联的且更灵活:一个锁实例,可以绑定多个Condition实例,实现多路通知;notify()方法进行通知时,是随机进行选择的,但重入锁结合Condition对象,可以实现有选择性的通知。
Condition接口API:
public interface Condition {
//阻塞当前线程。使当前线程加入等待队列中,同时释放当前锁,当其他线程使用signal()或者signalAll()方法时,线程会重新请求锁,得到锁后会继续执行。或者当线程被中断时,也能跳出等待。类似Object.wait()方法
void await() throws InterruptedException;
//调用该方法的前提是,当前线程已经成功获得与该Condition对象绑定的重入锁,否则调用该方法时会抛出IllegalMonitorStateException。
//基本同await()方法,但是不会在等待过程中响应中断。调用该方法后,结束等待的唯一方法是其它线程调用该条件对象的signal()或signalALL()方法。等待过程中如果当前线程被中断,该方法仍然会继续等待,同时保留该线程的中断状态。
void awaitUninterruptibly();
//调用该方法的前提是,当前线程已经成功获得与该Condition对象绑定的重入锁,否则调用该方法时会抛出IllegalMonitorStateException。
//等待的的最大时间(单位为纳秒)。若指定时间内收到signal()或signalALL()则返回nanosTimeout减去已经等待的时间;若指定时间内未收到通知,则返回0或负数。
//在等待过程中会响应中断,若指定时间内有其它线程中断该线程,则抛出InterruptedException并清除当前线程的打断状态。
long awaitNanos(long nanosTimeout) throws InterruptedException;
//与await()基本一致,不同点:指定时间之内没有收到signal()或signalALL()或线程中断会返回false;其它情况返回true。
boolean await(long time, TimeUnit unit) throws InterruptedException;
//与awaitNanos(long nanosTimeout)一致,不同点在于它不是等待指定时间,而是等待时间到达参数指定的某一时刻。
boolean awaitUntil(Date deadline) throws InterruptedException;
//唤醒一个等待队列中的线程。与Object.notify()相似,但是signal()唤醒的线程与该Condition对象有关
void signal();
//唤醒等待队列中所有线程。与object.notifyAll()相似,但是signalAll()唤醒的线程与该Condition对象有关
void signalAll();
}
代码Demo:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 可重入锁不同condition测试
*/
public class MyReentrantLockCondition implements Runnable {
//共享锁
public static ReentrantLock lock = new ReentrantLock();
//condition不共享
public Condition condition;
//共享变量
//public static volatile int i = 1;
public MyReentrantLockCondition() {
//每个对象独立condition
this.condition = lock.newCondition();
}
public void await() {
//自旋获取锁,直到获取锁成功
lock.lock();
try {
System.out.println("-->await(): " + Thread.currentThread().getName() + " 获取了锁");
//当前线程等待,释放了锁。类比Object.wait()。多线程操作共享变量是否有问题?没有问题,唤醒时会重新获取锁重新获取值
condition.await();
System.out.println("-->await(): " + Thread.currentThread().getName() + " 结束执行");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//任何情况都释放锁对象
lock.unlock();
}
}
public void signal() {
lock.lock();
try {
//唤醒等待队列中关联condition的一个线程.类比Object.notify()
condition.signal();
} finally {
lock.unlock();
}
}
//测试
public static void main(String[] args) throws InterruptedException {
MyReentrantLockCondition condition1 = new MyReentrantLockCondition();
MyReentrantLockCondition condition2 = new MyReentrantLockCondition();
MyReentrantLockCondition condition3 = new MyReentrantLockCondition();
MyReentrantLockCondition condition4 = new MyReentrantLockCondition();
new Thread(condition1).start();
new Thread(condition2).start();
new Thread(condition3).start();
new Thread(condition4).start();
Thread.sleep(3000);
//通知线程继续执行
condition1.signal();
condition2.signal();
// condition3.signal();
/* MyReentrantLockCondition.lock.lock();
try {
condition4.condition.signalAll();
} finally {
MyReentrantLockCondition.lock.unlock();
}*/
}
@Override
public void run() {
await();
}
}
运行main()方法,可看到结果:
-->await(): Thread-0 获取了锁
-->await(): Thread-1 获取了锁
-->await(): Thread-2 获取了锁
-->await(): Thread-3 获取了锁
-->await(): Thread-0 结束执行
-->await(): Thread-1 结束执行
Thread-2、Thread-3没有“结束执行”,还在一直等待signal()唤醒。
Condition在JDK源码中的应用:
java.util.concurrent.ArrayBlockingQueue阻塞队列:基于数组的阻塞队列实现,在ArrayBlockingQueue内部,维护了一个定长数组,以便缓存队列中的数据对象,还保存着两个整形变量,分别标识着队列的头部和尾部在数组中的位置。
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
final Object[] items;
int takeIndex;
int putIndex;
int count;
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
//往队列中添加对象
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();//自旋获取锁
try {
while (count == items.length)//队列已满
notFull.await();//进入等待队列中等待,关联notFull条件
enqueue(e);
} finally {
lock.unlock();
}
}
//队列中移除对象
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];
items[takeIndex] = null;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();//唤醒一个等待队列中等待notFull条件的线程
return x;
}
}