我在java类中有两个方法,它们都有一个使用同一对象进行同步的代码块。我明白,在JAVA同步方案中,线程获取的锁是可重入的。有了这个我可以安全地说下面的一段代码不会在所有情况下导致任何问题?使用同步语句的可重入同步行为
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
谢谢Tomasz Stanczak!在输入示例代码时,我错过了通过对象引用键入实例方法调用的方法。请耐心等待并答复答复。只要添加到我以前的查询中,当某个线程当前在method2内执行(从method1调用)时,如果某个其他线程试图执行方法1或方法3中的同步代码,我们可以肯定地说第二个线程将被阻塞,直到第一个线程完成执行方法1,方法2和方法3? – Muthu 2011-04-26 19:00:59
是的,它会阻塞,直到释放锁,并且当第一个线程从method3和method2返回后离开方法1中的同步块时会发生这种情况。 – 2011-04-27 06:47:00