[英]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 letn
be an integer such thatT
is then'th
lexically enclosing type declaration of the class whose declaration immediately contains the method invocation. 否则,令T
为方法是其成员的封闭类型声明,令n
为整数,使得T
为该类的第n'th
词法封闭类型声明,其声明立即包含方法调用。 The target reference is then'th
lexically enclosing instance of this. 目标引用是此n'th
第n'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,因为Outer
是Inner
的立即封闭类型声明。 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.