使用synchronized语句的可重入同步行为 [英] Reentrant synchronization behavior with synchronized statements
问题描述
我在java类中有两个方法,它们都有一个使用同一个对象同步的代码块。据我所知,在JAVA同步方案中,线程获取的锁是可重入的。有了这个,我可以安全地说下面的代码片段在所有情况下都不会引起任何问题吗?
I have two methods in a java class that both have a block of code that synchronize using the same object. I understand that in the JAVA synchronization scheme locks acquired by a thread are reentrant. With this can i safely say the below piece of code will not cause any issues in all cases?
public class Someclass
{
private static final Object LCK_OBJ = new Object();
//.....
publc void method1()
{
//some code....
synchronized(LCK_OBJ)
{
//some sychronized code.
method2(..);
}
//some more code....
}
protected static final void method2(..)
{
Someclass ref = null;
//some code which gets different other references of SomeClass in a loop....
ref.method3(..);
}
publc void method3()
{
//some code....
synchronized(LCK_OBJ)
{
//some sychronized code.
}
//some more code....
}
}//end of class
推荐答案
是的,但是这段代码不能编译:你从静态调用实例方法method3方法method2。除此之外:如果一个线程设法在method1中获取一个锁,如果仍然在method3中有锁。
Yes you can, but this code won't compile: you are calling an instance method "method3" from a static method "method2". Other than that: if a thread has managed to aquire a lock in "method1" if will still have the lock in "method3".
这篇关于使用synchronized语句的可重入同步行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!