Multithreading | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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 Respostas
+ 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