如果我在同一个类上同步了两个方法,它们可以同时运行吗? [英] If I synchronized two methods on the same class, can they run simultaneously?
问题描述
如果我在同一个类上同步了两个方法,它们可以同时在同一个对象上运行吗?例如:
If I synchronized two methods on the same class, can they run simultaneously on the same object? For example:
class A {
public synchronized void methodA() {
//method A
}
public synchronized void methodB() {
// method B
}
}
我知道我不能在两个不同的线程中对同一个对象运行两次 methodA()
.methodB()
中的相同内容.
I know that I can't run methodA()
twice on same object in two different threads. same thing in methodB()
.
但是我可以在 methodA()
仍在运行时在不同的线程上运行 methodB()
吗?(同一个对象)
But can I run methodB()
on different thread while methodA()
is still running? (same object)
推荐答案
两种方法都锁定同一个监视器.因此,您不能在来自不同线程的同一个对象上同时执行它们(两个方法中的一个将阻塞,直到另一个完成).
Both methods lock the same monitor. Therefore, you can't simultaneously execute them on the same object from different threads (one of the two methods will block until the other is finished).
这篇关于如果我在同一个类上同步了两个方法,它们可以同时运行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!