Java wait() not Throwing InterruptedException
I have an object on thread A that is calling wait()
while another object on thread B does some work then calls thread A's object's notify()
. Thread A then performs 开发者_开发百科some post-processing.
My problem is pretty straightforward:
synchronized(this)
{
while(!flag)
{
try
{
wait();
getLogger().info("No longer waiting");
}
catch (InterruptedException ie)
{
getLogger().info("Wait threw InterruptedException");
}
}
}
Results in an info message of "No longer waiting" instead of "Wait threw InterruptedException".
I am confused, because of this (http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait()):
Throws:
InterruptedException - if another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Why am I getting odd behavior?
Thanks.
When a thread waits using wait()
, he actually waits for notify()
. So once notify()
has been called by the other thread, this thread will continue, if you will call interrupt()
, you would get the exception.
Also, from the documents you linked to:
Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object
notify
releases the thread from the lock.
InterruptedException - if another thread interrupted the current thread before or while the current thread was waiting for a notification.
notify()
does not make wait()
throw InterruptedException
. notify()
let wait()
continue the normal program flow.
notify()
is not an abnormal termintation for a thread that is wait()
-ing. You'd get the exception if, for instance, the thread was terminated before notify()
was called - not as a result of notify()
being called. The thread hasn't been interrupted - it's been awoken.
Note that you have a bug in that code. Wait should always be invoked in a loop, and check a condition after waking up.
wait can be awaken by a spurious wakeup. See the javadoc wait()
精彩评论