I know the difference between those two was already discussed not once, but still don't really understand it in practice, for example here (K&B book, Chapter 9)
Regardless of whether I use notify() or notifyAll() in lines 26-27, all three Reader threads get notified and print their messages:
Thread[Thread-1,5,main]: Waiting for calculation...
Thread[Thread-3,5,main]: Waiting for calculation...
Thread[Thread-2,5,main]: Waiting for calculation...
Thread[Thread-2,5,main]: Total is: 4950
Thread[Thread-3,5,main]: Total is: 4950
Thread[Thread-1,5,main]: Total is: 4950
Well the calculator thread will notify only one thread if notify() is used, which thread its unpredictable. But when the calculator thread completes, it calls its own notifyall() method. So if you have some thread which are joined(calculator.join()) to the end of calculator thread will be notified when the calculator thread completes. notifyAll() is called as soon as the run method ends. I suppose you can try this behaviour commenting out both notify and notifyall. Well as found out this is an unexpected behaviour of the thread. It can be avoided and to really check the notify and notifyall, implement Runnable as it is advised to that in most cases using threads. Make CalcReader and Calculator implementing the Runnable interface and start these runnables using new Thread(runnable).start() . May be you will see the expected behaviour then. Well there is problem here if the calculator runs first calling the notifyAll and then the other 3 threads, then again this program will no end. Well then you can use setPriority() and make use of MAX_PRIORITY, MIN_PRIORITY and NORM_PRIORITY over using numbers from 1 to 10 more like this
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
Andre Enimot wrote:Nitish, Ninad, thank you for explaining. Oooooo that's a big one! So notifyAll() is called automatically by any run() method after it completes! I don't think this is mentioned in the K&B book, is it.
No it isn't, and you don't need to know that for the exam as it is an implementation detail of the API which can change (actually this has been implemented like this because of the join method, search the forum for more details)...
Yes you don't need to know that.. Just can get the concept that's all. Also its based on how join works that's all which is not needed to know it detail. Also not by any run but only the thread's run method and not runnable's run method.