为什么notify方法应该在synchronized块内呢? [英] Why should the notify method be inside a synchronized block?

查看:85
本文介绍了为什么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?

推荐答案


notify()应该给信号所有线程都在等待。

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

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

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆