Wednesday 18 November 2015

Explain about inter thread communication ? Why wait, notify, notifyAll methods are in Object class

Inter-thread communication: It is all about allowing synchronized threads to communicate with each other. It is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class.
a. wait() b. notify() c. notifyAll()
wait(): It Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.
The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception


S.No
Method
Description
1
public final void wait()throws InterruptedException
waits until object is notified
2
public final void wait(long timeout)throws InterruptedException
waits for the specified amount of time
notify(): Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
Syntax: public final void notify()
notifyAll(): Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()
Note: Above 3 methods are in object class because they are related to lock and object has a lock.
Explanation of Inter thread Communication:
The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.

2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

No comments:

Post a Comment