Java notfiyAll()没有唤醒主线程

时间:2011-04-15 16:28:31

标签: java wait

我正在尝试使用notifyAll()和wait()来处理另一段代码。所以我创建了一个与其他程序类似的新程序。

我的程序让我的主线程创建了一个单独的线程,它将在20秒后运行notifyAll(),我的主线程将等待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

1 个答案:

答案 0 :(得分:4)

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

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