我想知道在 Java 中如果我在同一个对象上同步两次是否会出现任何奇怪的行为?
场景如下
pulbic class SillyClassName {
object moo;
...
public void method1(){
synchronized(moo)
{
....
method2();
....
}
}
public void method2(){
synchronized(moo)
{
doStuff();
}
}
}
两种方法都使用对象并在其上同步。第二个方法被第一个方法调用时会因为被锁定而停止吗?
我不这么认为,因为它是同一个线程,但我不确定可能会出现任何其他奇怪的结果。
最佳答案
可重入
同步块(synchronized block)使用重入锁,这意味着如果线程已经持有锁,它可以重新获取它而不会出现问题。因此,您的代码将按预期工作。
见底部 Java Tutorial页 Intrinsic Locks and Synchronization .
自 2015 年 1 月起引用……
Reentrant Synchronization
Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.
关于java - 在同一个对象上同步两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/249867/