Java: A synchronized method in the superclass acquires the same lock as one in the subclass, right?

后端 未结 7 830
闹比i
闹比i 2021-02-12 10:12
class A {
    public synchronized void myOneMethod() {
        // ...
    }
}

class B extends A {
    public synchronized void myOtherMethod() {
        // ...
    }
}
         


        
7条回答
  •  无人及你
    2021-02-12 10:46

    Yes, you are right, and you got the explanation right too. Nothing much to add.

    Note that if the methods were static, then they would synchronize on different objects, namely their respective classes (A and B).

    EDIT: Why am I sure? I don't know, why are you not sure? ;-) myObject is just one object - there isn't any distinction between the myObject attributes that come from class A and those that come from class B. (Well, technically you could probably use reflection to find out which are which, so there must be some distinction, but forget about reflection for now. For common operations on the object there's no distinction.)

提交回复
热议问题