Originally posted by mark stone:
ragu, then what's the point of notifyAll instead of notify. In the end only one thread gets the monitor or lock. i guess i am missing something here.
its like saying this is a candy (one only) and i got to give it one of you guys. One way is just whisper so that one guys hears it and he gets it. The other is I shout that here is a candy and all you guys want it now. But then after all i just pick one of you guys and he gets the candy.
so what's the big deal here ! i guess i am missing something here.
Good point.. Well here is how it is..
From JLS:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
There is no rule that notify must be used in a single threaded or single thread competeing environment. It is even applicable to a multi-threaded environment But from a programmer's prespective you choose to notify a single thread that's all. To co-relate to your analogy... you tell the class teacher (our jvm implementation ) that you wanna give this candy to a kid. The kids have no clue about your candy . It is the class-teacher decides which kid to get based on (certain criteria, in case of jvm priority based or round robin or something else...)and informs that kid alone
In a way it is very discriminating since most of the threads wont even have an opportunity to content for the lock..(most of the kids dont even know that you have a candy to give...)
notifyAll:
From JLS:
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.
In this case , you inform all the kids that you have a candy and you play a fair role of broadcasting the message but then again you give the candy to the class-teacher who has the final authority to give it based on the criteria...
In both the case the lock/candy is just one.
The participation to content varies from a single thread to multiple threads
HIH
Ragu