我正在尝试让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/