Causes the current thread to wait until either another thread invokes the
java.lang.Object.notify()
method or the
java.lang.Object.notifyAll()
method for this object, or a
specified amount of time has elapsed.
The current thread must own this object's monitor.
This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:
notify
method for this
object and thread T happens to be arbitrarily chosen as
the thread to be awakened.
notifyAll
method for this
object.
timeout
is zero, however, then real time is not taken into
consideration and the thread simply waits until notified.
wait
method was invoked. Thread T then returns from the
invocation of the wait
method. Thus, on return from the
wait
method, the synchronization state of the object and of
thread T
is exactly as it was when the wait
method
was invoked.
A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:
synchronized (obj) { while (<condition does not hold>) obj.wait(timeout); ... // Perform action appropriate to condition }(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).
If the current thread is java.lang.Thread.interrupt() by any thread before or while it is waiting, then an
InterruptedException
is thrown. This exception is not
thrown until the lock status of this object has been restored as
described above.
Note that the wait
method, as it places the current thread
into the wait set for this object, unlocks only this object; any
other objects on which the current thread may be synchronized remain
locked while the thread waits.
This method should only be called by a thread that is the owner
of this object's monitor. See the notify
method for a
description of the ways in which a thread can become the owner of
a monitor.
timeout | the maximum time to wait in milliseconds. |
IllegalArgumentException | if the value of timeout is negative. | |
IllegalMonitorStateException | if the current thread is not the owner of the object's monitor. | |
InterruptedException | if any 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. |
java.lang.Object.notify(), java.lang.Object.notifyAll()
Diagram: Object