扩展类同步方法锁定

use*_*926 5 java concurrency multithreading

假设这段代码

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

class B extends A
{
    @Override
    public synchronized void methodA()
    {
        // ...
        super.methodA();
    }
}
Run Code Online (Sandbox Code Playgroud)

什么锁应该被任何线程,如果它想通过访问B类和超A级的了methodA功能了methodA被收购super.methodA()

Mat*_*ens 2

方法synchronized相当于其主体包裹在synchronized(this)块中的方法。因此,这个:

public synchronized void methodA()
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

是相同的:

public void methodA()
{
    synchronized(this) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以轻松地看到这两个methodA实现都锁定同一个对象,即this对象。也就是说,如果一个线程处于超类synchronized的方法中,它也会阻止其他线程进入子类的任何方法(反之亦然)。synchronized

由于synchronized锁是可重入的,成功进入B.methodA意味着你也可以立即进入super.methodA(因为你已经拥有锁了)。