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

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

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

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

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


当前回答

清楚地说,静态同步和非静态同步方法都可能同时或并发地运行,因为一个有对象级锁,另一个有类级锁。

其他回答

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

你同步的是对象而不是类。所以它们不能同时在同一物体上运行

从oracle文档链接

使方法同步有两个效果:

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. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads

这将回答您的问题:在同一个对象上,当第一个同步方法正在执行时,您不能调用第二个同步方法。

看看这个文档页,了解内在锁和锁的行为。

将您的代码想像如下所示:

class A {

public void methodA() {
    synchronized(this){        
      //method A body
    }
}

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

因此,在方法级别上同步仅仅意味着同步(这个)。 如果任何线程运行该类的方法,它将在开始执行之前获得锁,并持有它直到方法执行完成。

但是我可以在不同的线程上运行methodB()而methodA()仍然是 跑步吗?(同一对象)

的确,这是不可能的!

因此,多个线程将不能同时在同一个对象上运行任意数量的同步方法。

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