Java中线程等待与唤醒通过wait()、notify()、notifyAll()实现,需在synchronized中调用;示例为生产者-消费者模型,使用共享资源的同步方法控制线程间通信。

在Java中实现线程的等待与唤醒,主要依赖于
Object
wait()
notify()
notifyAll()
synchronized
IllegalMonitorStateException
wait():使当前线程释放锁并进入等待状态,直到其他线程调用同一个对象的
notify()
notifyAll()
notify():唤醒在此对象监视器上等待的单个线程。选择是任意的。
notifyAll():唤醒所有在此对象监视器上等待的线程。
立即学习“Java免费学习笔记(深入)”;
red">注意:这三个方法都必须在synchronized
下面是一个简单的生产者-消费者模型,演示线程等待与唤醒机制:
class SharedResource {
private int data;
private boolean hasData = false;
public synchronized void produce(int value) throws InterruptedException {
while (hasData) {
wait(); // 等待消费者消费
}
data = value;
hasData = true;
System.out.println("生产了: " + data);
notify(); // 唤醒等待的消费者线程
}
public synchronized void consume() throws InterruptedException {
while (!hasData) {
wait(); // 等待生产者生产
}
System.out.println("消费了: " + data);
hasData = false;
notify(); // 唤醒等待的生产者线程
}
}
public class WaitNotifyExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
try {
resource.produce(i);
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
Thread consumer = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
try {
resource.consume();
Thread.sleep(800);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
producer.start();
consumer.start();
}
}
synchronized
while
if
notify()
notifyAll()
从Java 5开始,可以使用
java.util.concurrent.locks.Condition
import java.util.concurrent.locks.*;
class BetterSharedResource {
private int data;
private boolean hasData = false;
private final Lock lock = new ReentrantLock();
private final Condition hasDataCondition = lock.newCondition();
private final Condition noDataCondition = lock.newCondition();
public void produce(int value) throws InterruptedException {
lock.lock();
try {
while (hasData) {
noDataCondition.await(); // 等待空位
}
data = value;
hasData = true;
System.out.println("生产了: " + data);
hasDataCondition.signal(); // 唤醒消费者
} finally {
lock.unlock();
}
}
public void consume() throws InterruptedException {
lock.lock();
try {
while (!hasData) {
hasDataCondition.await(); // 等待数据
}
System.out.println("消费了: " + data);
hasData = false;
noDataCondition.signal(); // 唤醒生产者
} finally {
lock.unlock();
}
}
}
这种方式的优势在于一个Lock可以创建多个Condition,实现更精确的线程控制。
基本上就这些。核心是理解等待/唤醒机制背后的锁与条件判断逻辑,避免死锁和误唤醒。以上就是如何在Java中实现线程等待与唤醒的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号