notifyAll和wait方法是用來進(jìn)行線程間通信的。
當(dāng)一個(gè)線程調(diào)用wait方法時(shí),它會(huì)釋放對(duì)象的鎖,并進(jìn)入等待狀態(tài),直到其他線程調(diào)用notifyAll方法來喚醒它。
下面是一個(gè)簡單的示例代碼,演示了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類有一個(gè)消息字段和setMessage、getMessage方法。sender線程通過調(diào)用setMessage方法來設(shè)置消息,receiver線程通過調(diào)用getMessage方法來獲取消息。當(dāng)receiver線程調(diào)用getMessage方法時(shí),如果消息字段為null,它會(huì)調(diào)用wait方法進(jìn)入等待狀態(tài),直到sender線程調(diào)用setMessage方法設(shè)置消息并調(diào)用notifyAll方法來喚醒receiver線程。
在實(shí)際應(yīng)用中,notifyAll和wait方法通常會(huì)和synchronized關(guān)鍵字一起使用,以確保線程安全。此外,notifyAll方法會(huì)喚醒所有等待的線程,而不是喚醒一個(gè)特定的線程。