The Object class in JavaSW has three final methods that allow threads to communicate about the locked status of a resource. These methods are wait(), notify(), and notifyAll(). A thread obtains a lock for a particular resource via a synchronized block with an instance of that resource. Suppose that a thread requires that another thread perform a certain action on the resource before it acts on the resource. That thread can synchronize on the resource and call the wait() method on resource. This says that the thread will wait until it has been notified that it can proceed to act. The wait() method can take an optional timeout value as a parameter. If this value is used, it means that the thread will either wait until it's notified or it will continue to execute once the timeout value has passed.
If a thread is required to perform a task on a resource before another thread operates on the resource (and the other thread is waiting via the wait() method on the resource), the thread needs synchronize on the resource. It can perform its actions on the resource. In order to notify the waiting thread once these actions have completed, the notify() method on the resource is called. This notifies the waiting thread that it can proceed to act. If multiple threads are waiting for the resource, there is no guarantee as to which thread will be given access to the resource. If it is desired for all waiting threads to be awoken, the notifyAll() method can be called on the resource.
wait/notify is that it avoids polling (checking over and over to see if a resource is ready to be used), since polling can be expensive in terms of system resources.
Waiter is waiting for the notifier at Fri Feb 07 18:09:12 EST 2014
Notifier is sleeping for 3 seconds at Fri Feb 07 18:09:12 EST 2014
Notifier is notifying waiting thread to wake up at Fri Feb 07 18:09:15 EST 2014
Waiter is done waiting at Fri Feb 07 18:09:15 EST 2014
Waiter got the message: Notifier took a nap for 3 seconds
|Impossible to extract MSI from new JAVA releases||2||47|
|Java - sorting a list of objects where the properties of the objects can change during the sort||7||45|
|replace a word with other||1||40|
|reverse digits of a number using for loop||5||36|
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
20 Experts available now in Live!