本文介绍了为什么notify方法应该在synchronized块内呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码: -

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
        }
    }
} 

另一个类通过在同步块内获取锁定来等待该类的实例。但是,如果我不在同步块中保存run方法中的代码,那么我得到 IllegalMonitorStateException

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()应该向所有等待的线程发出信号。那为什么它应该在同步块内呢?

notify() should mean to give signal to all the threads waiting. Then why should it be inside synchronized block?

推荐答案

实际上,没有。它发出一个任意选择的等待线程的信号。 notifyAll()表示所有这些信号。

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

因为等待不是为了它自己的缘故。你检查一个条件,如果它没有达到,你要等到有人告诉你它现在可以满足(然后你再次检查)。如果没有同步,您将在检查条件和实际等待之间遇到竞争条件。

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.

这篇关于为什么notify方法应该在synchronized块内呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 03:55