Java notfiyAll() 不唤醒主线程

标签 java wait

我正在尝试让notifyAll() 和wait() 为另一段代码工作。因此,我创建了一个新程序,其行为与其他程序类似。

我的程序让我的主线程创建一个单独的线程,该线程将在 20 秒后运行 notificationAll(),而我的主线程将等待 60 秒。因此,在单独的线程调用notifyAll()之前,我的主线程应该有足够的时间来调用wait()。但问题是我的主线程没有从notifyAll()中唤醒并等待了整整60秒。为什么这不起作用?

我的代码如下所示:

new Thread(new Runnable(){
    public void run(){
        synchronized (this){
            try{
                this.wait(20000);
                System.out.println("Wait 20 seconds then notify");
                this.notifyAll();
            } catch (Exception e){}
        }
    }
}, "test Thread").start();
System.out.println("started thread");

boolean timeout = false;
System.out.println("Start Waiting");
synchronized (this){
    try{
        this.wait(60000);
        timeout = true;
    } catch(Exception e){
        System.out.println("Did not wait 60 seconds");
    }
}
if (timeout){
    System.out.println("Waited 60 Seconds");
}

我得到的输出是:

started thread
Start Waiting
Wait 20 seconds then notify
Waited 60 Seconds

最佳答案

wait 和notify 必须使用相同的对象引用才能工作。在这种情况下,您的通知使用 Runnable 实例,而您的等待使用主类实例。

您可以通过在 Runnable 实例中同步“MainClass.this”来修复它(使用主类的任何名称)。

关于Java notfiyAll() 不唤醒主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5679698/

相关文章:

java - 在 Java Swing 中等待鼠标输入

c - 等待 fork 的 child ,直到它启动另一个程序

java - Android:使用两个 ValueEventListener 从 firebase 数据库获取数据(在 Arraylist 过期之前设置适配器)

java - java中的字符串格式化程序对于$%2$.2f意味着什么

抛出异常的函数的 Java 字段初始化

javascript - 如何创建 JavaScript 延迟函数

database - 延迟或等待声明

java - 验证金额应为整数类型的方法返回类型

java - Checkstyle,如何强制序列化 ID 的存在?

node.js - Nodejs 在循环中等待