Hello, this is an exampl from SCJP 6 book (Sierra, Bates) about threads. But i dont works as it should i I dont know why... Can somebody help?
If I understand it well, when I call notify() method, one thread which waits for this objects lock move from blocked state do runnable. And when I call notifyAll() all threads move in the same way.
But then following code dont work as it should:
So the result should be only one Thread ends. But there all always more outputs. So three threads Reader were created and each take a lock and sleep 100 milis, but meanwhile thread Calculator starts and notify one thread. It is possible that when it calls notify(), just the first thread should sleep so no output sould be done. But what is strange, is that notifies 1, 2 or 3 threads.
Another strange thing is that when i comment CENTRAL POINT row, so Calculator dont notify anybody, program always make output. Shouldn't it just stop, because of waiting threads? The same thing if i remove synchronized block from Calculator.
The core libraries use it to implement the join() method -- when a thread finishes, a notifyAll() is sent (using the Thread object) to wake up all threads that are waiting to join. Hi Henry, I guess notify() or notifyAll() for waking up Threads are used only with wait().(not with join())
kri shan wrote:Hi Henry, I guess notify() or notifyAll() for waking up Threads are used only with wait().(not with join())
Please read my post again. I never said notifyAll() is supposed to be called to wake up threads that call join(). I said that there is a call to notifyAll() that is called automatically, as part of the thread shutdown process, to wake up threads that call the join() method. The join() method is implemented using a loop that checks the alive flag, and call the wait() method.