notifyall与wait方法如何配合使用
导读:notifyAll和wait方法是用来进行线程间通信的。 当一个线程调用wait方法时,它会释放对象的锁,并进入等待状态,直到其他线程调用notifyAll方法来唤醒它。 下面是一个简单的示例代码,演示了notifyAll和wait方法的配...
notifyAll和wait方法是用来进行线程间通信的。
当一个线程调用wait方法时,它会释放对象的锁,并进入等待状态,直到其他线程调用notifyAll方法来唤醒它。
下面是一个简单的示例代码,演示了notifyAll和wait方法的配合使用:
public class Message {
private String message;
public synchronized void setMessage(String message) {
this.message = message;
notifyAll();
}
public synchronized String getMessage() {
while (message == null) {
try {
wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
return message;
}
}
public class Main {
public static void main(String[] args) {
Message message = new Message();
Runnable sender = () ->
{
message.setMessage("Hello from sender!");
}
;
Runnable receiver = () ->
{
String receivedMessage = message.getMessage();
System.out.println("Received message: " + receivedMessage);
}
;
Thread senderThread = new Thread(sender);
Thread receiverThread = new Thread(receiver);
senderThread.start();
receiverThread.start();
}
}
在上面的示例中,Message类有一个消息字段和setMessage、getMessage方法。sender线程通过调用setMessage方法来设置消息,receiver线程通过调用getMessage方法来获取消息。当receiver线程调用getMessage方法时,如果消息字段为null,它会调用wait方法进入等待状态,直到sender线程调用setMessage方法设置消息并调用notifyAll方法来唤醒receiver线程。
在实际应用中,notifyAll和wait方法通常会和synchronized关键字一起使用,以确保线程安全。此外,notifyAll方法会唤醒所有等待的线程,而不是唤醒一个特定的线程。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: notifyall与wait方法如何配合使用
本文地址: https://pptw.com/jishu/686261.html