都知道 AQS 的 Node 节点里有个 nextWaiter 节点,这个 nextWaiter 节点就是在 Condition 里面用的。

是什么

首先 Condition 是一个接口,里面定义了很多方法

  1. public interface Condition {
  2. void await() throws InterruptedException;
  3. void awaitUninterruptibly();
  4. long awaitNanos(long nanosTimeout) throws InterruptedException;
  5. boolean await(long time, TimeUnit unit) throws InterruptedException;
  6. boolean awaitUntil(Date deadline) throws InterruptedException;
  7. void signal();
  8. void signalAll();
  9. }

其中最重要的就是 await() 和 signal() 方法,即提供简单的阻塞(等待)和唤醒功能。而所谓的“条件”其实是我们在外部业务层定义的。

先来看看用法吧:Condition 经常可以用在生产者-消费者的场景中,请看 Doug Lea 给出的这个例子:

  1. class BoundedBuffer {
  2. final Lock lock = new ReentrantLock();
  3. // condition 依赖于 lock 来产生
  4. final Condition notFull = lock.newCondition();
  5. final Condition notEmpty = lock.newCondition();
  6. final Object[] items = new Object[100];
  7. int putptr, takeptr, count;
  8. // 生产
  9. public void put(Object x) throws InterruptedException {
  10. lock.lock();
  11. try {
  12. while (count == items.length)
  13. notFull.await(); // 队列已满,等待,直到 not full 才能继续生产
  14. items[putptr] = x;
  15. if (++putptr == items.length) putptr = 0;
  16. ++count;
  17. notEmpty.signal(); // 生产成功,队列已经 not empty 了,发个通知出去
  18. } finally {
  19. lock.unlock();
  20. }
  21. }
  22. // 消费
  23. public Object take() throws InterruptedException {
  24. lock.lock();
  25. try {
  26. while (count == 0)
  27. notEmpty.await(); // 队列为空,等待,直到队列 not empty,才能继续消费
  28. Object x = items[takeptr];
  29. if (++takeptr == items.length) takeptr = 0;
  30. --count;
  31. notFull.signal(); // 被我消费掉一个,队列 not full 了,发个通知出去
  32. return x;
  33. } finally {
  34. lock.unlock();
  35. }
  36. }
  37. }

我们可以看到,在使用 condition 时,必须先持有相应的锁。这个和 Object 类中的方法有相似的语义,需要先持有某个对象的监视器锁才可以执行 wait(), notify() 或 notifyAll() 方法。

如何生成 Condition 对象

很简单,使用 newCondition() 方法即可。

  1. final ConditionObject newCondition() {
  2. return new ConditionObject();
  3. }

有意思的是,这个 ConditionObject 类也是 AQS 的内部类,它实现了 Condition 接口。来看看 ConditionObject 有哪些关键的属性:

  1. public class ConditionObject implements Condition, java.io.Serializable {
  2. private transient Node firstWaiter;
  3. /** Last node of condition queue. */
  4. private transient Node lastWaiter;
  5. }

它有两个关键属性,firstWaiter 和 lastWaiter。从注释可以看出来,lastWaiter 是条件队列里的最后一个 Node 节点。

阻塞

调用 await() 方法即可阻塞。

  1. public final void await() throws InterruptedException {
  2. if (Thread.interrupted())
  3. throw new InterruptedException();
  4. // 添加到 condition 的条件队列中
  5. Node node = addConditionWaiter();
  6. // 释放锁,返回值是释放锁之前的 state 值
  7. // await() 之前,当前线程是必须持有锁的,这里肯定要释放掉
  8. int savedState = fullyRelease(node);
  9. int interruptMode = 0;
  10. // 1. isOnSyncQueue(node) 返回 true,即当前 node 已经转移到阻塞队列了
  11. while (!isOnSyncQueue(node)) {
  12. LockSupport.park(this);
  13. if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
  14. break;
  15. }
  16. // 被唤醒后,进入阻塞队列,等待获取锁
  17. if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
  18. interruptMode = REINTERRUPT;
  19. if (node.nextWaiter != null) // clean up if cancelled
  20. unlinkCancelledWaiters();
  21. if (interruptMode != 0)
  22. reportInterruptAfterWait(interruptMode);
  23. }

这里有两个需要注意的地方:

  1. isOnSyncQueue(Node node) 用于判断节点是否已经转移到等待队列了:
  2. 执行到下面的 acquireQueued 时,证明该节点已经转移到等待队列里了,准备抢锁。

唤醒

调用 signal() 方法执行唤醒

  1. public final void signal() {
  2. // 调用 signal 方法的线程必须持有当前的独占锁
  3. if (!isHeldExclusively())
  4. throw new IllegalMonitorStateException();
  5. Node first = firstWaiter;
  6. if (first != null)
  7. doSignal(first);
  8. }
  9. // 从条件队列队头往后遍历,找出第一个需要转移的 node
  10. // 因为前面我们说过,有些线程会取消排队,但是可能还在队列中
  11. private void doSignal(Node first) {
  12. do {
  13. if ( (firstWaiter = first.nextWaiter) == null)
  14. lastWaiter = null;
  15. first.nextWaiter = null;
  16. } while (!transferForSignal(first) &&
  17. (first = firstWaiter) != null);
  18. }

总结一下:signal() 大概做的事情就是将条件队列里的第一个节点 firstWaiter 转移到等待队列里。


总结

来看看 lock 和 condition 的关系。
Condition - 图1

  1. 条件队列和阻塞队列的节点,都是 Node 的实例,因为条件队列的节点是需要转移到阻塞队列中去的;
  2. 我们知道一个 ReentrantLock 实例可以通过多次调用 newCondition() 来产生多个 Condition 实例,这里对应 condition1 和 condition2。注意,ConditionObject 只有两个属性 firstWaiter 和 lastWaiter;
  3. 每个 condition 有一个关联的条件队列,如线程 1 调用 condition1.await() 方法即可将当前线程 1 包装成 Node 后加入到条件队列中,然后阻塞在这里,不继续往下执行,条件队列是一个单向链表;
  4. 调用condition1.signal() 触发一次唤醒,此时唤醒的是队头,会将condition1 对应的条件队列的 firstWaiter(队头) 移到阻塞队列的队尾,等待获取锁,获取锁后 await() 方法才能返回,继续往下执行。

与 wait() 和 notify() 的关系

其实你会发现,这里的 condition.await() 和 object.wait() 以及 condition.signal() 和 object.notify() 很像,就像是 ReentrantLock 为了实现 Synchronized 对应的 wait() 和 notify() 方法而发明出来的。

比如:

  1. synchronized (object1) {
  2. // 释放锁
  3. // 阻塞,等待被其他线程notify()
  4. // 重新拿锁
  5. object1.wait();
  6. }

可以看出来使用 wait() 也是要先获得锁(先获得 ReentrantLock 的 lock),然后会进入等待池里(进入了等待队列中)等着被唤醒(执行 signal() 方法),即执行 object1.notify()。然后有重新进入了锁池准备枪锁。