notifyAll()用于唤醒所有等待特定对象监视器的线程,需在synchronized块中调用,配合wait()实现线程协作,如生产者-消费者模型中通过notifyAll()确保多个消费者或生产者被唤醒,避免线程阻塞。

在Java中,notifyAll() 用于唤醒所有正在等待特定对象监视器的线程。它通常与 synchronized 块、wait() 方法配合使用,实现线程间的协作。下面介绍如何正确使用 notifyAll() 来唤醒线程。
这三个方法都定义在 Object 类中,必须在 synchronized 上下文中调用:
以下是一个生产者-消费者模型的简单示例,展示如何用 notifyAll() 正确唤醒多个等待线程:
import java.util.LinkedList;
import java.util.Queue;
public class NotifyAllExample {
private final Queue<String> queue = new LinkedList<>();
private final int MAX_SIZE = 3;
public void produce(String item) throws InterruptedException {
synchronized (this) {
while (queue.size() == MAX_SIZE) {
System.out.println("队列已满,生产者等待...");
this.wait(); // 释放锁并等待
}
queue.add(item);
System.out.println("生产了: " + item);
this.notifyAll(); // 唤醒所有等待线程(包括消费者)
}
}
public String consume() throws InterruptedException {
synchronized (this) {
while (queue.isEmpty()) {
System.out.println("队列为空,消费者等待...");
this.wait(); // 释放锁并等待
}
String item = queue.poll();
System.out.println("消费了: " + item);
this.notifyAll(); // 唤醒所有等待线程(包括生产者)
return item;
}
}
}启动多个生产者和消费者线程,观察 notifyAll 如何唤醒多个等待线程:
立即学习“Java免费学习笔记(深入)”;
public class TestNotifyAll {
public static void main(String[] args) {
NotifyAllExample example = new NotifyAllExample();
// 启动多个消费者线程
for (int i = 1; i <= 3; i++) {
new Thread(() -> {
try {
while (true) {
example.consume();
Thread.sleep(2000); // 模拟处理时间
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "Consumer-" + i).start();
}
// 启动生产者线程
new Thread(() -> {
int counter = 1;
try {
while (true) {
example.produce("item-" + counter++);
Thread.sleep(500);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "Producer").start();
}
}使用 notifyAll() 时需注意以下几点:
基本上就这些。notifyAll() 是实现线程协作的重要工具,合理使用可避免死锁和线程饥饿问题。
以上就是如何在Java中使用notifyAll唤醒线程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号