从同步方法中调用方法 [英] Calling a method from within a synchronized method

查看:68
本文介绍了从同步方法中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临一个奇怪的问题,这使我想知道同步方法中到底发生了什么.假设有一种方法

I'm facing a strange problem which has made me wonder what exactly happens in a synchronized method. Let's say there is a method

synchronized public void example(){
     //...code
     int i=call(); //calling another method
     //...do something with i 
}

现在,当执行call()方法时,另一个对象可以输入此同步的example()方法吗?因此,当call()返回时,可能会出现一些ConcurrentModificationException吗?为了避免出现问题该怎么办?

Now while the call() method is being executed, can another object enter this synchronized example() method? So when the call() returns, there might be some ConcurrentModificationException? What to do in order to avoid problems?

推荐答案

请注意,在此示例中,如果call()不是私有的或从类中的其他地方调用的,则其他人可以中断您的认为是一个完全同步的过程.

Note that in this example, if call() isn't private or is called from somewhere else in the class, someone else can interrupt what you think is an entirely synchronous process.

synchronized void a(){
    println 'hello'
    b();
    println 'world'
}

void b(){

}

如果您期望"a的所有内容都可以通过同步来保护",那么如果b完全没有副作用,那么如果synchronized void a以外的方法调用b,则该保证将丢失.

If you expect "everything that a does to be guarded by synchronized", then if b has any side-effects at all, that guarantee is lost if methods other than synchronized void a call b.

这篇关于从同步方法中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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