Why should the notification method be inside the synchronized block?

Consider the following code: -

class CalculateSeries implements Runnable{
    int total;
    public void run(){
        synchronized(this){                          // *LINE 1* 
            for(int i = 1; i <= 10000; i++) {
                total += i;
            }

            notify(); //Notify all the threads waiting on this instance of the class to wake up
        }
    }
} 

Another instance expects an instance of this class, getting its lock inside the synchronized block. But if I do not save the code in the run method in a synchronized block, then I get IllegalMonitorStateException.

notify()should indicate a signal for all pending threads. Then why should it be inside a synchronized block?

+5
source share
1 answer

notify () should indicate a signal for all pending threads.

No, actually. It signals one arbitrarily selected waiting stream. notifyAll()signals all of them.

Then why should it be inside a synchronized block?

. , , , - , ( ). .

+4

All Articles