意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

notifyall与wait方法如何配合使用

来源:佚名 编辑:佚名
2024-07-04 14:00:28

notifyAll和wait方法是用来进行线程间通信的。

当一个线程调用wait方法时,它会释放对象的锁,并进入等待状态,直到其他线程调用notifyAll方法来唤醒它。

下面是一个简单的示例代码,演示了notifyAll和wait方法的配合使用:


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方法会唤醒所有等待的线程,而不是唤醒一个特定的线程。

本网站发布或转载的文章均来自网络,其原创性以及文中表达的观点和判断不代表本网站。
上一篇: 在Java中notifyall的具体实现方式 下一篇: 如何正确使用notifyall避免死锁