![](/img/trans.png)
[英]Calling a synchronized method from another synchronized method, both on different object
[英]Calling a method from within a synchronized method
我面临一个奇怪的问题,这使我想知道同步方法中到底发生了什么。 假设有一种方法
synchronized public void example(){
//...code
int i=call(); //calling another method
//...do something with i
}
现在,在执行call()方法时,另一个对象可以输入此同步的example()方法吗? 因此,当call()返回时,可能会出现一些ConcurrentModificationException吗? 为了避免出现问题该怎么办?
不,它不能。 同步方法基本上与以下方法相同:
public void example(){
synchronized(this){
//do stuff
}
}
请注意,在此示例中,如果call()
不是私有的或从类中的其他位置调用的,则其他人可以中断您认为是完全同步的过程。
synchronized void a(){
println 'hello'
b();
println 'world'
}
void b(){
}
如果您期望“ a的所有内容都可以通过同步来保护”,那么如果b根本没有任何副作用,那么,如果非synchronized void a
方法synchronized void a
调用b
synchronized void a
,则该保证将丢失。
当线程进入Synchronized方法时,将发生锁定,直到该方法返回(直到您调用call()
之后call()
,该锁定才会释放。
这是一篇关于锁和同步的好文章: http : //download.oracle.com/javase/tutorial/essential/concurrency/locksync.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.