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

后端 未结 7 1002
闹比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:26

    If you want to be more explicit about your locking, you could do something like this:

    class A {
    
        protected final Object  mutex = new Object();
        public void myOneMethod() {
            synchronized (mutex) {
                // ...
            }
        }
    }
    
    class B extends A {
        public  void myOtherMethod() {
            synchronized (mutex) {
                // ...
            }
        }
    }
    

    In fact, this pattern is recommended by Brian Goetz in Java Concurrency in Practice, section 4.2.1 "The Java monitor pattern". That way you know exactly where your monitor is coming from.

提交回复
热议问题