【问题标题】:synchronized method in derived class派生类中的同步方法
【发布时间】:2013-11-19 13:36:21
【问题描述】:

如果基类 A 具有未被其派生类 B 覆盖的“public synchronized void method(){}”,则 用于访问 B 类中的同步方法的锁是什么(即是派生类对象还是基类对象)?

【问题讨论】:

  • 不是静态方法,是吗?
  • No. 甚至没有像 synchronized(A.class) 或 synchronized(getClass()) 或 synchronized(Class.forName("A")) 那样的块同步

标签: java multithreading locking synchronized


【解决方案1】:

没有“基类对象”。

synchronized 方法锁定它们被调用的实例。

【讨论】:

    【解决方案2】:
    public synchronized void method() {  
        ...
    };
    

    一样
    public void method() {  
        synchronized(this){
            ...
        }
    };
    

    对于超级方法this 表示B 类的对象。所以锁将在对象B的一个实例上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 2018-05-16
      • 2017-06-22
      • 2017-10-12
      • 2021-07-18
      相关资源
      最近更新 更多