简体   繁体   中英

Why should the notify method be inside a 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 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?

notify() should mean to give signal to all the threads waiting.

Actually, no. It signals one arbitrarily chosen waiting thread. notifyAll() signals all of them.

Then why should it be inside synchronized block?

Because waiting doesn't happen for its own sake. You check for a condition and if it's not met, you wait until someone tells you it may now be met (then you check again). Without synchronization, you would have race conditions between checking the condition and actually waiting.

if notify() method is not within synchronized block then it would be useless to place wait() into synchronized block.
Take scenario of producer-consumer model, producer and consumer both the methods will execute concurrently because one of them is not synchronized. There will be a race condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM