从内部 class 调出 class' 同步方法

Calling outer class' syncronized method from inner class

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

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

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

Inner.run()在调用doSomething()时获得了哪个锁?它与 synchronized(Inner.this)synchronized(Outer.this) 相同吗?

非常感谢。

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

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

Otherwise, let T be the enclosing type declaration of which the method is a member, and let n be an integer such that T is the n'th lexically enclosing type declaration of the class whose declaration immediately contains the method invocation. The target reference is the n'th lexically enclosing instance of this.

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

Concerning synchronized methods,JLS 表示

For an instance method, the monitor associated with this (the object for which the method was invoked) is used.