The Object class in java contains three final methods that allows threads to communicate about the lock status of a resource. These methods are wait(), notify()
and notifyAll()
. The current thread which invokes these methods on any object should have the object monitor else it throws java.lang.IllegalMonitorStateException exception.
wait() method
In Object class the wait method has three variance, one which waits indefinitely for any other thread to call notify or notifyAll method on the object to wake up the current thread. Other two variances puts the current thread in wait for specific amount of time before they wake up.
notify() method
notify method wakes up only one thread waiting on the object and that thread starts execution. So if there are multiple threads waiting for an object, this method will wake up only one of them. The choice of the thread to wake depends on the OS implementation of thread management.
notifyAll() method
notifyAll method wakes up all the threads waiting on the object, although which one will process first depends on the OS implementation.
Here follows a sample multithreaded program which explain the usage of wait()
and notify()
Here the output become follows
The thread Second Thread before wait executing The thread First Thread before wait executing The thread Second Thread got notified
Here in line number 15 it used notify()
. So it will inform only one thread to wakeup from wait state. If you are used notifyAll()
instead of notify()
the output looks like follows
The thread First Thread before wait executing The thread Second Thread before wait executing The thread Second Thread got notified The thread First Thread got notifiedWhich means it will notify all other threads which is in waiting state.
No comments:
Post a Comment