Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java notfiyAll()未唤醒主线程_Java_Wait - Fatal编程技术网

Java notfiyAll()未唤醒主线程

Java notfiyAll()未唤醒主线程,java,wait,Java,Wait,我试图让notifyAll()和wait()为另一段代码工作。因此,我创建了一个新程序,其行为与另一个程序类似 我的程序让我的主线程创建一个单独的线程,该线程将在20秒后运行notifyAll(),而我的主线程将等待60秒。因此,在单独的线程调用notifyAll()之前,我的主线程应该有足够的时间调用wait()。但问题是我的主线程没有从notifyAll()中唤醒,而是等待了整整60秒。为什么这不起作用 我的代码如下所示: new Thread(new Runnable(){ pub

我试图让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

wait和notify必须使用相同的对象引用才能工作。在本例中,notify使用Runnable实例,而wait使用的是main类实例


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

等待和通知必须使用相同的对象引用才能工作。在本例中,notify使用Runnable实例,而wait使用的是main类实例


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

换句话说,添加line Object lock=this;在最顶端,然后同步,等待并通知“lock”。换言之,添加行Object lock=this;在最顶端,然后同步,等待并通知“锁定”。