Multithreading | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

19th Jul 2020, 6:43 AM
Gauri Shirkande
Gauri Shirkande - avatar
5 Answers
+ 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.
19th Jul 2020, 7:45 AM
A͢J
A͢J - avatar
+ 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.
19th Jul 2020, 7:46 AM
A͢J
A͢J - avatar
+ 2
It was really helpful 🙌
19th Jul 2020, 7:55 AM
Gauri Shirkande
Gauri Shirkande - avatar
+ 1
Thanks👍
19th Jul 2020, 7:45 AM
Gauri Shirkande
Gauri Shirkande - avatar