Monday, 5 December 2016

Why wait, notify and notifyAll are not inside thread class ?

These methods works on the locks and locks are associated at Object level not at Thread level.So, that's why these methods belongs to Object class.The methods wait(), notify() and notifyAll() are also used for inter-thread communication in Threads.

In Java, Synchronization make sure that only one thread will access the object or resources at one time.

In Java, any object can act as a monitor, An object's method without qualifed by the keyword synchronized  can be invoked by any number of  threads at any time, the lock is ignored. 
The synchronized method of an object, who owns the lock of that object, can be permitted to run that method at any time i.e. a synchronized method is mutually exclusive .If, at the time of invocation, another thread owns the lock, then the calling thread will be put in the Blocked state and is added to the entry queue.

When a thread running in a synchronized method of an object is calling the wait() method of the same object, that thread releases the lock of the object and is added to that object's waiting queue. As long as it's there, it sits idle.
Note also that wait() forces the thread to release its lock. This means that it must own the lock of an object before calling the wait() method of that (same) object. Hence the thread must be in one of the object's synchronized methods or synchronized block before calling wait().



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment