I have a thread program where I was testing the thread notify method. But it didn't work
I am not getting the results.
There is one class that performs a calculation and many readers that are waiting to receive the completed calculation. At any given moment many readers may be waiting.
So I am using the notifyall() method to notify all the waiting threads to move to runnable.
But I am not getting the final output and also the total is still prints 0 ( if I replace c.wait() with Thread.sleep(100))
Also note that if your calculator gets its lock first, it would complete and send the notifyAll() signal before any of the readers get the lock and wait() on it. That would mean that some or all of your readers may (sometimes) never be notified.
But please not the situation I noted in the previous post, if the calculator gets the lock first it would finish and notifyAll() before readers where waiting on it. Starting that thread last is not enough to ensure that doesn't happen as thread execution order is not guaranteed.
Steve is right. You should add more significant delay into a calculator. But is not your main problem.
You main problem is that there are no threads to notify! Notify/notifyAll notifies only threads waiting on a montor. And "waiting" threads are the only threads which implicitly invoked one of Object.wait methods on a monitor object. Also you should know that waiting on a monitor will release lock on that monitor untill that thread will be wakened up, interrupted or timeout exipred. Thus while some threads are waiting other thread may acquire the same lock. Thread.sleep does not release any locks so no other thread can acquire monitor while that thread is sleeping. And you ends up having one sleeping thread with a lock or a calculator and no waiting threads. So you need to use one of Object.wait methods. Read javadocs for all of them to find that one which matches you intentions best.