开发者

Java notfiyAll() not waking main thread

开发者 https://www.devze.com 2023-02-25 15:52 出处:网络
I am trying to get notifyAll() and wait() to work for another piece of code. So I created a new program t开发者_StackOverflowhat behaves similarly to the other program.

I am trying to get notifyAll() and wait() to work for another piece of code. So I created a new program t开发者_StackOverflowhat behaves similarly to the other program.

My program has my main thread create a separate thread that will run notifyAll() after 20 seconds, and my main thread will wait for 60 seconds. So there should be plenty of time for my main thread to call wait() before the separate thread calls notifyAll(). But the problem is that my main thread does not wake up from the notifyAll() and waits the full 60 seconds. Why is this not working?

My code looks like this:

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");
}

And the output I get is:

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


wait and notify must use the same object reference in order to work. in this case, your notify is using the Runnable instance, and your wait is using the main class instance.

you could fix it by synchronizing on "MainClass.this" in the Runnable instance (using whatever the name of the main class is).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号