简体   繁体   中英

Wait notify infinite loop

I have the following infinite loop in java:

    while (!Thread.interrupted())
    {
        synchronized (this)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {
                logger.error(e);
                Thread.currentThread().interrupt();
            }
        }
    }

This is the body of a runForever() method for an application. That application has a shutdown hook attached so that a method named stop() will be executed when it gets control-c-ed

The question is, why does this works? The thread is waiting forever, who does notify this thread so it stops waiting?

As per the Javadoc for java.lang.Object ...

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0) . The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

... so the thread will wait indefinitely as per the behavior you've described unit notify() or notifyAll() is called. As for the second part of your question, it's also in the JavaDoc:

Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

This also explains a bit as to why wait() waits indefinitely. The reason it does is because calling wait() is the same as calling wait(0) , in which case " thread simply waits until notified " as per the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM