如果我在同一个类上同步了两个方法,它们能同时在同一个对象上运行吗?例如:

class A {
    public synchronized void methodA() {
        //method A
    }

    public synchronized void methodB() {
        // method B
    }
}

我知道我不能在两个不同的线程中对同一个对象运行methodA()两次。在methodB()中也是如此。

但我可以运行methodB()在不同的线程,而methodA()仍在运行?(同一对象)


当前回答

Two different Threads executing a common synchronized method on the single object, since the object is same, when one thread uses it with synchronized method, it will have to verify the lock, if the lock is enabled, this thread will go to wait state, if lock is disabled then it can access the object, while it will access it will enable the lock and will release the lock only when it's execution is complete. when the another threads arrives, it will verify the lock, since it is enabled it will wait till the first thread completes his execution and releases the lock put on the object, once the lock is released the second thread will gain access to the object and it will enable the lock until it's execution. so the execution will not be not concurrent, both threads will execute one by one, when both the threads use the synchronized method on different objects, they will run concurrently.

其他回答

这两种方法都锁定同一个监视器。因此,你不能同时从不同的线程在同一个对象上执行它们(两个方法中的一个会阻塞,直到另一个方法完成)。

Two different Threads executing a common synchronized method on the single object, since the object is same, when one thread uses it with synchronized method, it will have to verify the lock, if the lock is enabled, this thread will go to wait state, if lock is disabled then it can access the object, while it will access it will enable the lock and will release the lock only when it's execution is complete. when the another threads arrives, it will verify the lock, since it is enabled it will wait till the first thread completes his execution and releases the lock put on the object, once the lock is released the second thread will gain access to the object and it will enable the lock until it's execution. so the execution will not be not concurrent, both threads will execute one by one, when both the threads use the synchronized method on different objects, they will run concurrently.

Java线程在进入实例同步Java方法时获得一个对象级锁,在进入静态同步Java方法时获得一个类级锁。

在您的示例中,方法(实例)属于同一个类。因此,当一个线程进入java synchronized方法或块时,它会获得一个锁(方法被调用的对象)。因此,在第一个方法完成并释放lock(on object)之前,不能在同一对象上同时调用其他方法。

不,这是不可能的,如果这是可能的,那么这两个方法可以同时更新同一个变量,这很容易破坏数据。

在你的例子中,你在同一个类实例上同步了两个方法。所以,这两个方法不能同时运行在类A的同一个实例的不同线程上,但是它们可以运行在不同的类A实例上。

class A {
    public synchronized void methodA() {
        //method A
    }
}

等于:

class A {
    public void methodA() {
        synchronized(this){
            // code of method A
        }
    }
}