Why wait and notify is declared in the Object class instead of Thread?

By | March 7, 2023

The wait() and notify() methods are declared in the Object class rather than the Thread class because they are used for inter-thread communication, which involves threads interacting with shared objects. Since every object in Java has an intrinsic lock (also known as a monitor), it makes sense to provide these methods in the Object class so that any object can be used for inter-thread communication.

The wait() method causes the current thread to wait until another thread notifies it, while the notify() method wakes up a single thread that is waiting on the same object’s monitor. These methods are used to coordinate the actions of multiple threads that share a common object, enabling them to communicate with each other in a synchronized manner.

If these methods were declared in the Thread class, it would imply that they are specific to thread objects only, which is not the case. By declaring them in the Object class, any object can be used as a shared resource for inter-thread communication, allowing for more flexible and fine-grained synchronization between threads.

Leave a Reply

Your email address will not be published. Required fields are marked *