简体   繁体   English

从内部类调用外部类的同步方法

[英]Calling outer class' syncronized method from inner class

I have a program that looks in essence like this 我有一个本质上看起来像这样的程序

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

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

Which lock does Inner.run() acquire when it is calling doSomething() ? Inner.run()调用doSomething()时会获得哪个锁? Is it identical to synchronized(Inner.this) or synchronized(Outer.this) ? 它是否与synchronized(Inner.this)synchronized(Outer.this)

Thanks a lot in advance. 非常感谢。

The receiver for the invocation of doSomething() within run() is Outer.this . run()调用doSomething()的接收者是Outer.this The synchronized will therefore lock the monitor on the object referenced by that expression. 因此, synchronized将把监视器锁定在该表达式引用的对象上。

On computing the target reference in a method invocation expression , the JLS says 计算方法调用表达式中的目标引用时 ,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. 否则,令T为方法是其成员的封闭类型声明,令n为整数,使得T为该类的第n'th词法封闭类型声明,其声明立即包含方法调用。 The target reference is the n'th lexically enclosing instance of this. 目标引用是此n'thn'th词汇包围的实例。

T here is Outer , since that's the class that declares it. T这里是Outer ,因为这是声明它的类。 n is 1, as Outer is the immediately enclosing type declaration of Inner . n为1,因为OuterInner的立即封闭类型声明。 The target reference is therefore the 1'th lexically enclosing instance of this , ie. 因此,目标引用是this第1个词法包围实例。 Outer.this . Outer.this

Concerning synchronized methods , the JLS says 关于synchronized方法 ,JLS说

For an instance method, the monitor associated with this (the object for which the method was invoked) is used. 对于实例方法,使用与this相关联的监视器(为其调用方法的对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM