这个问题在这里已经有了答案:
Java synchronize block on same object in different methods
(2 个回答)
1年前关闭。
假设我在一个方法中同步了两部分代码。所以 block1 和 block2 周围都有关键字 'synchronized',并且都使用 'this',这意味着两个 block 都由同一个对象锁保护。
现在如果block1正在被一个线程执行,是否意味着没有其他线程可以执行block2?
最佳答案
在方法声明上同步是一样的:
public void method() {
synchronized (this) {
// method code
}
}
话虽如此,正如您在 oracle docs 中看到的那样你可以看到一个带有一些同步方法的例子,它说:First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
所以,是的,在这种情况下,没有其他线程可以执行 block2 。
关于java - 在同一方法中同步多个 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62738571/