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 class is waiting on an instance of this class by getting the lock on it inside a synchronized block. But if I don't keep the code in run method in a synchronized block, then I get IllegalMonitorStateException
.
notify()
should mean to give signal to all the threads waiting. Then why should it be inside synchronized block?