我对 Java 同步有疑问。我想知道我的类中是否有三个 Synchronized 方法,一个线程在一个同步方法中获取锁,另外两个将被锁定?我问这个问题是因为我对以下陈述感到困惑。
While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread
最佳答案
Java 中的同步是通过获取某个特定对象上的监视器来完成的。因此,如果您这样做:
class TestClass {
SomeClass someVariable;
public void myMethod () {
synchronized (someVariable) {
...
}
}
public void myOtherMethod() {
synchronized (someVariable) {
...
}
}
}
然后这两个 block 将随时通过执行 2 个不同的线程来保护,同时 someVariable
不会被修改。基本上,据说这两个 block 是针对变量 someVariable
同步的。
当你把synchronized
放在方法上时,它的意思基本上和synchronized(this)
一样,就是在这个方法执行的对象上同步。
即:
public synchronized void myMethod() {
...
}
含义相同:
public void myMethod() {
synchronized (this) {
...
}
}
因此,要回答您的问题 - 是的,线程将无法在不同线程中同时调用这些方法,因为它们都持有对同一监视器的引用,即 this
的监视器对象。
关于java - 同步如何在 Java 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11184642/