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

后端 未结 7 823
闹比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:40

    Yes. Java uses "monitors" to implement synchronization, and synchronized methods use the object instance they're called on as monitor, which is obviously the same in this case.

    Note that this is NOT true for static methods! There, the class instance of (I think) the declaring class is used, which would not be the same one.

提交回复
热议问题