在 java 的 synchronized 中,避免虚假唤醒的唯一可靠方法是使用 while 循环来包裹 wait() 调用,而不是使用 if 条件判断。这是因为线程被唤醒后,必须重新检查等待的条件是否真正满足,以应对其他线程可能已经修改了状态或发生竞争的情况。

为什么 if 判断会导致错误?
如果使用 if 语句,当线程从 wait() 返回时,它假设条件已经成立并直接继续执行。然而,由于虚假唤醒(Spurious Wakeup)或其他线程的竞争,条件可能实际上并未满足。这会导致程序逻辑错误,例如消费者在没有数据的情况下尝试消费,从而抛出异常或处理空值。

public class Consumer implements Runnable {
private final Queue<string> queue;
public Consumer(Queue<string> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
// 错误的做法:使用 if
if (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
// 如果发生虚假唤醒,这里会尝试从空队列获取元素
String item = queue.poll();
System.out.println("Consumed: " + item);
}
}
}
}</string></string>
while 循环如何确保安全性?
使用 while 循环会在每次唤醒后重新评估条件。如果条件不满足(例如队列仍为空),线程将再次进入 wait() 状态。只有当条件真正满足时,循环才会退出,线程才能安全地执行后续逻辑。这是处理共享状态变更的标准模式。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

public class SafeConsumer implements Runnable {
private final Queue<string> queue;
public SafeConsumer(Queue<string> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
// 正确的做法:使用 while
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
// 此时可以确信队列非空
String item = queue.poll();
System.out.println("Consumed: " + item);
}
}
}
}</string></string>
notifyAll 与 notify 的选择对虚假唤醒的影响
虽然 while 循环解决了虚假唤醒的逻辑问题,但使用 notify() 而非 notifyAll() 可能会加剧竞争条件。当多个生产者或消费者存在时,notify() 只唤醒一个线程,该线程醒来后发现条件不满足(因为另一个线程先获取了锁并改变了状态),它会再次 wait()。而 notifyAll() 会唤醒所有等待的线程,它们都会通过 while 循环重新检查条件,只有条件满足的线程才会继续执行。因此,结合 while 和 notifyAll() 是最稳健的做法。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










