简体   繁体   English

Java:在超类方法上同步

[英]Java: synchronize on superclass method

abstract class Basic (){
    public synchronized void basicMethod(String string){
        //Some actions here
    }
}

public class A extends Basic{
    public void aMethod(){
        //Some actions here
    }
}

public class B extends Basic{
    public void bMethod(){
        //Some actions here
    }
}

Basic a = new A();
Basic b = new B();

a.basicMethod(); // acquires lock
b.basicMethod(); //Same lock?

In other words - lock is related to concrete Object or Super class important too? 换句话说-锁与具体的Object或Super类是否也重要?

Different locks. 不同的锁。 A synchronized instance method synchronizes on the monitor associated with that particular object instance , so each of a and b has its own monitor. synchronized实例方法在与特定对象实例关联的监视器上进行同步,因此ab都有自己的监视器。

If you had 如果你有

abstract class Basic (){
    public synchronized void basicMethod(String string){
        //Some actions here
    }
}

public class A extends Basic{
    public synchronized void aMethod(){
        //Some actions here
    }
}

then calls to a.basicMethod() and a.aMethod() would lock the same monitor. 然后调用a.basicMethod()a.aMethod()将锁定同一监视器。

Though both a & b acquire a lock, these locks are associated to the object reference. 尽管a & b获得了一个锁,但是这些锁都与对象引用相关联。 So a & b will both be able to enter their synchronized region at the same point by acquiring different locks. 因此, a & b都可以通过获取不同的锁来在同一点进入其同步区域。

In other words - lock is related to concrete Object or Super class important too? 换句话说-锁与具体的Object或Super类是否也重要?

The lock is related to the object instance. 锁与对象实例有关。

As far as I know, a lock is held on an object reference, not on the class definition. 据我所知,锁是持有对象引用,而不是类定义。 This means that those would be two different locks, as they are not held on the same object reference. 这意味着它们将是两个不同的锁,因为它们没有保存在同一对象引用上。 Remember, every object in Java is a subclass of the Object class, so if it were the case that it locks on the highest superclass, it would only ever be possible to have one lock in a program. 请记住,Java中的每个对象都是Object类的子类,因此,如果它锁定了最高的超类,则在程序中只能锁定一个。

There are different lock, as lock is held on a object . 有不同的锁,因为锁保持在object Javadoc says Javadoc

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. 当一个线程正在执行对象的同步方法时,所有其他调用同一对象块的同步方法的线程(挂起执行),直到第一个线程对该对象完成。

Basic a = new A();
Basic b = new B();

Each one a and b have different object reference so have different locks thus call to synchornized method with two different locks will happan. 每个ab具有不同的对象引用,因此具有不同的锁,因此调用具有两个不同锁的同步化方法会发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM