Java Reference
In-Depth Information
public final void notify()
Notifies at most one thread waiting for a condition to change.
You cannot choose which thread will be notified, so use this
form of notify only when you are sure you know which
threads are waiting for what at which times. If you are not
sure of any of these factors, you should use notifyAll .
If no threads are waiting when either notifyAll or notify is invoked, the
notification is not remembered. If a thread subsequently decides to wait ,
an earlier notification will have no effect on it. Only notifications that oc-
cur after the wait commences will affect a waiting thread.
You can invoke these methods only from within synchronized code, us-
ing the lock for the object on which they are invoked. The invocation
can be directly made from the synchronized code, or can be made in-
directly from a method invoked in such code. You will get an IllegalMon-
itorStateException if you attempt to invoke these methods on an object
when you don't hold its lock.
When a wait completes because the time-out period expires, there is no
indication that this occurred rather than the thread being notified. If a
thread needs to know whether or not it timed out, it has to track elapsed
time itself. The use of a time-out is a defensive programming measure
that allows you to recover when some condition should have been met
but for some reason (probably a failure in another thread) has not. Be-
cause the lock of the object must be reacquired, the use of a time-out
cannot guarantee that wait will return in a finite amount of time.
It is also possible that some virtual machine implementations will allow
so-called "spurious wakeups" to occurwhen a thread returns from wait
without being the recipient of a notification, interruption, or time-out.
This is another reason that wait should always be performed in a loop
that tests the condition being waited on.
Exercise 14.6 : Write a program that prints the elapsed time each
second from the start of execution, with another thread that prints a
message every fifteen seconds. Have the message-printing thread be
 
Search WWH ::




Custom Search