Multithreading | Sololearn: Learn to code for FREE!

+1

Multithreading

If wait(), notify(), notifyAll() methods are only used in Multithreading then why are these methods present in Object class instead of Thread class?

7/19/2020 6:43:25 AM

Gauri Shirkande

6 Answers

New Answer

+4

Probably because you wait on Objects and notify Objects, threads is just one of the construct where you would do it. And probably everything is upcastable to Object class. Found this thread which is saying same and more https://stackoverflow.com/q/1769489/7986108

+4

Gauri Shirkande I found this on Stackoverflow:- In the Java language, you wait() on a particular instance of an Object – a monitor assigned to that object to be precise. If you want to send a signal to one thread that is waiting on that specific object instance then you call notify() on that object. If you want to send a signal to all threads that are waiting on that object instance, you use notifyAll() on that object. If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread. How would thread1 know that thread2 was waiting for access to a particular resource? If thread1 needed to call thread2.notify() it would have to somehow find out that thread2 was waiting. There would need to be some mechanism for threads to register the resources or actions that they need so others could signal them when stuff was ready or available.

+4

Gauri Shirkande Continue.......... In Java, the object itself is the entity that is shared between threads which allows them to communicate with each other. The threads have no specific knowledge of each other and they can run asynchronously. They run and they lock, wait, and notify on the object that they want to get access to. They have no knowledge of other threads and don't need to know their status. They don't need to know that it is thread2 which is waiting for the resource – they just notify on the resource and whomever it is that is waiting (if anyone) will be notified.

+2

for many reasons, see : https://www.quora.com/Why-notify-wait-notifyAll-methods-are-defined-in-Object-class-in-java

+2

It was really helpful 🙌

+1

Thanks👍