Why wait, notify and notifyAll is defined in Object Class?
Why wait, notify and notifyAll are not defined in Thread Class?
Above questions are very popular in interview. Interviewer will often ask this question to test the knowledge of wait(), notify() and notifyAll() methods in Java multithreading. This is very important question because it also clears the concept of a Thread and Lock. Now lets see why wait(), notify() and notifyAll(), these methods are in Object class and not in Thread Class.
Reasons why wait, notify and notifyAll are defined in Object Class
In java there is a concept of Monitor (What is monitor in java?) , each object has a monitor. So when a thread perform a wait operation, the operation involves two things a Thread and a Monitor. When a thread which currently owns a monitor object can suspend itself inside the monitor with the help of Wait method what it do is it releases the monitor object and enters in a wait state. The wait state ends when another thread call notify method inside the monitor object. So wait and notify methods happens on any object which threads are accessing to. So this is a main reason to have wait, notify and notifyAll is defined in Object Class.
Also the wait and notify are communication mechanisms used by the objects to communicate between two thread.
Also Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.
Also as these wait(), notify() and notifyAll() methods are defined in the Object class all objects in java can able to use it.
We will see what these methods do ?
Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
Wakes up a single thread that is waiting on this object’s monitor
Wakes up all threads that are waiting on this object’s monitor.
Thus we have seen why wait(), notify() and notifyAll() methods are defined in the Object Class and not in Thread class.