+ 1

How does wait() method work in java ?

How do threads communicate using wait() and notify()/notifyAll()? and Why are these methods present in Object class rather than Thread class?

12th Mar 2018, 2:15 AM
Satyam Joshi
Satyam Joshi - avatar
4 ответов
+ 1
Hello, About classes, you need to know that any object is build with a lock, also called monitor. These monitors are used when you use a synchronized method. but in some case, you may need to wait an event before doing some action (for example, the reader-consumer problem). To do that, you use the method wait. and when the condition is ok, you can call notify, to notify a thread waiting with the wait method to run again, or notifyAll, to notify all suspended thread. Evidently, you should use wait inside a loop which check if the condition is satisfied.
12th Mar 2018, 9:57 PM
Xavier Heugue
Xavier Heugue - avatar
+ 1
the goal of join is to wait a thread to complete. the goal of wait is to do nothing before a specific condition is satisfied
13th Mar 2018, 4:47 AM
Xavier Heugue
Xavier Heugue - avatar
0
what if we use join() instead of wait? a thread will still wait until the completion of the other thread, then why is wait() required?
12th Mar 2018, 11:55 PM
Satyam Joshi
Satyam Joshi - avatar
0
you can find the "producer consurmer" problem here: https://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/ it contains an example
13th Mar 2018, 4:54 AM
Xavier Heugue
Xavier Heugue - avatar