Java Interview Qn Threads – Why Java has added wait(),notify() methods in Object class, even when we don’t use it

MultiThreading Java Interview Quesion?

We all know, the mother of all classes i.e Object class has wait(), notify(), notifyall() methods. Now question is, many times we don’t write a program which is multithreaded, then Why Object class wait() and notify() methods. They could have been a part of some interface, so as to use when on need basis.

Answer

In Java, Threads wait on a instance of a Object(o1), this is also called a monitor or semaphore. While one thread(t1) is executing the business logic, other thread(t2) waits on the instance of the object till the notify() / notifyAll() is called.
Now if, wait() and notify() were not a part of the Object, they you cannot wait on them, and you cannot add the methods in Thread class, as multiple threads need to share the instance of an object for multithreading to work.
So In Conclusion, In Multithreaded programs, multiple threads wait on a instance of an Object, and this instance is shared by all threads, hence it should be in Object only.

Comments

Popular posts from this blog

Apache Airflow Wait Between Tasks

Groovy GoodNess – Converting a List to String

Java Spring Interview Questions