报告不是在循环中进行的 wait() 调用。

wait() 通常用于挂起线程,直到某个条件变为 true 为止。 由于线程可能出于不同的原因而被唤醒,因此在 wait() 调用返回后应检查条件。 使用循环很容易做到这一点。

示例:


  class BoundedCounter {
    private int count;
    synchronized void inc() throws InterruptedException {
      if (count >= 10) wait();
      ++count;
    }
  }

优良的代码应类似于:


  class BoundedCounter {
    private int count;
    synchronized void inc() throws InterruptedException {
      while (count >= 10) wait();
      ++count;
    }
  }