Java Reference
In-Depth Information
The
Object
class defines the methods
wait()
,
notify()
, and
notifyAll()
, which you can use to
provide a more efficient way of dealing with this kind of situation. Since all classes are derived from
Object
,
all classes inherit these methods. You can only call these methods from within a
synchronized
method, or
from within a synchronized code block, and an exception of type
IllegalMonitorStateException
will
be thrown if you call them from somewhere. The functions that these methods perform are:
Method
Description
wait()
There are three overloaded versions of this method.
This version suspends the current thread until the
notify()
or
notifyAll()
method is called for the object to which the
wait()
method belongs. Note that when any version of
wait()
is called, the
thread releases the synchronization lock it has on the object, so any
other method or code block synchronized on the same object can
execute. As well as enabling
notify()
or
notifyAll()
to be
called by another thread, this also allows another thread to call
wait()
for the same object.
Since all versions of the
wait()
method can throw an
InterruptedException
, you must call it in a
try
block with a
catch
block for this exception, or at least indicate that the method
calling it throws this exception.
wait(long timeout)
This version suspends the current thread until the number of
milliseconds specified by the argument has expired, or until the
notify()
or
notifyAll()
method for the object to which the
wait()
method belongs is called, if that occurs sooner.
wait(long timeout,
int nanos)
This version works in the same way as the previous version, except
the time interval is specified by two arguments, the first in
milliseconds, and the second in nanoseconds.
notify()
This will restart a thread that has called the
wait()
method for the
object to which the
notify()
method belongs. If several threads
have called
wait()
for the object, you have no control over which
thread is notified, in which case it is better to use
notifyAll()
. If
no threads are waiting, the method does nothing.
notifyAll()
This will restart all threads that have called
wait()
for the object to
which the
notifyAll()
method belongs.
The basic idea of the
wait()
and
notify()
methods is that they provide a way for methods or code
blocks that are synchronized on a particular object to communicate. One block can call
wait()
to
suspend its operation until some other method or code block synchronized on the same object changes
it in some way, and calls
notify()
to signal that the change is complete. A thread will typically call
wait()
because some particular property of the object it is synchronized on is not set, or some
condition is not fulfilled, and this is dependent on action by another thread. Perhaps the simplest
situation is where a resource is busy because it is being modified by another thread, but you are by no
means limited to that.