notify()唤醒单个等待线程,notifyAll()唤醒所有等待线程;示例中通过synchronized、wait()与notifyAll()实现生产者-消费者模型,确保线程安全通信。

在Java中,
notify()
notifyAll()
notify()
notifyAll()
解决方案
使用
notify()
notifyAll()
synchronized
wait()
class Message {
private String msg;
private boolean empty = true;
public synchronized String read() {
while (empty) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
empty = true;
notifyAll(); // 通知生产者可以生产
return msg;
}
public synchronized void write(String msg) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
empty = false;
this.msg = msg;
notifyAll(); // 通知消费者可以消费
}
}
class Reader implements Runnable {
private Message msg;
public Reader(Message msg) {
this.msg = msg;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
String message = msg.read();
System.out.println("Reader got: " + message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class Writer implements Runnable {
private Message msg;
public Writer(Message msg) {
this.msg = msg;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
msg.write("Message " + i);
System.out.println("Writer wrote: Message " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public class NotifyExample {
public static void main(String[] args) {
Message msg = new Message();
new Thread(new Reader(msg)).start();
new Thread(new Writer(msg)).start();
}
}这段代码展示了一个简单的生产者-消费者模型。
Message
Reader
Message
Writer
Message
synchronized
read()
write()
wait()
notifyAll()
立即学习“Java免费学习笔记(深入)”;
notify()
notifyAll()
notify()
notifyAll()
notify()
notifyAll()
为什么需要synchronized
synchronized
synchronized
synchronized
read()
write()
如何避免死锁?
死锁是指两个或多个线程互相等待对方释放资源,导致所有线程都无法继续执行的情况。 为了避免死锁,需要遵循一些最佳实践:
wait()
notify()
notifyAll()
synchronized
是的,
wait()
notify()
notifyAll()
synchronized
synchronized
IllegalMonitorStateException
除了wait()
notify()
notifyAll()
当然,Java提供了多种线程间通信的方式,除了
wait()
notify()
notifyAll()
ReentrantLock
Condition
ReentrantLock
synchronized
Condition
BlockingQueue
BlockingQueue
put()
take()
take()
put()
CountDownLatch
CountDownLatch
CyclicBarrier
CyclicBarrier
Exchanger
Exchanger
Exchanger
Semaphore
Semaphore
选择哪种线程间通信方式取决于具体的需求。 对于简单的生产者-消费者模型,
wait()
notify()
notifyAll()
ReentrantLock
Condition
BlockingQueue
以上就是如何在Java中使用notify和notifyAll的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号