【问题标题】:Calling outer class' syncronized method from inner class从内部类调用外部类的同步方法
【发布时间】:2016-06-01 22:52:53
【问题描述】:

我有一个本质上看起来像这样的程序

class Outer {
    class Inner implements Runnable {
        public void run() {
            doSomething();
        }
    }

    public synchronized void doSomething() {
        //...
    }
}

Inner.run() 在调用doSomething() 时会获取哪个锁?是否与synchronized(Inner.this) 或synchronized(Outer.this) 相同?

非常感谢。

【问题讨论】:

  • synchronized 与调用点无关。
  • Inner.this 和 Outer.this 不是 Java 中的有效代码。
  • @SamTebbs33 他们是。它们允许您针对内部类具体说明封闭实例。
  • @SotiriosDelimanolis 因为我几乎从不使用非静态内部类,所以我不知道!
  • @SamTebbs33 Nitpick,您几乎从不使用非静态 嵌套 类。 内部类是指非静态嵌套类。

标签: java inner-classes synchronized


【解决方案1】:

在run() 中调用doSomething() 的接收者是Outer.this。因此,synchronized 会将监视器锁定在该表达式引用的对象上。

在computing the target reference in a method invocation expression,JLS 说

否则,让T 成为其封闭类型声明 方法是一个成员,让n 是一个整数,这样T 就是n'th 其声明的类的词法封闭类型声明 立即包含方法调用。目标参考是 n'th 在词法上封闭 this 的实例。

T 这里是Outer,因为这是声明它的类。 n 是 1,因为 Outer 是 Inner 的直接封闭类型声明。因此,目标引用是this 的第一个词法封闭实例,即。 Outer.this.

Concerning synchronized methods,JLS 说

对于实例方法,与this(对象 调用该方法的对象)。

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2019-04-16
    • 2023-03-23
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多