简体   繁体   English

为什么notify方法应该在synchronized块中?

[英]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 . 但是如果我没有在同步块中保存run方法中的代码,那么我会得到IllegalMonitorStateException

notify() should mean to give signal to all the threads waiting. notify()应该意味着向所有等待的线程发出信号。 Then why should it be inside synchronized block? 那为什么它应该在同步块内呢?

notify() should mean to give signal to all the threads waiting. notify()应该意味着向所有等待的线程发出信号。

Actually, no. 实际上,没有。 It signals one arbitrarily chosen waiting thread. 它标志着一个任意选择的等待线程。 notifyAll() signals all of them. notifyAll()发出所有信号。

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. 如果notify()方法不在synchronized块内,那么将wait()放入synchronized块是没用的。
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. 会有竞争条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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