java - 同步如何在 Java 中工作?

标签 java thread-synchronization

我对 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/

相关文章:

java - 插入 SQLite 数据库 - Android

java - 使用 Jackson 将名称值对数组反序列化为对象

java - 如何在创建类时启动线程并(重新)使用它多次执行方法

java - 无法将 csv 文件导入 JAVA

java - JAXB XSLT 属性替换

java - 在 selenium 的表中断言多个值

c++ - 我们可以在 Sockets Map 上使用读写锁吗?

java - 回调中的 notify() 未发出 wait() 信号

c# - 如何防止一个应用程序的两个实例同时做同样的事情?