[英]synchronized method of the inner class
If a method of an inner class is marked as synchronized, which lock is actually acquired for this method?如果一个内部class的方法被标记为synchronized,那么这个方法实际获取的是哪个锁? The outer object or the inner object?外层 object 还是内层 object?
Initially, I think it is the inner object but when I saw a code snippet: sample inner class , stateMachine
is not even the member of the inner class but is the member of the outer class, so I wonder maybe the lock acquired is the outer object?最初,我认为它是内部 object 但是当我看到一个代码片段: 示例内部 class时, stateMachine
甚至不是内部 class 的成员而是外部 class 的成员,所以我想知道获取的锁是否是外部object?
Thank you谢谢
It will be synchronized on the Object the method is a member of.它将在方法所属的 Object 上同步。
public class SyncTest{
class B{
synchronized void runTest(){
System.out.println("running");
}
}
synchronized void check() throws Exception{
B b = new B();
new Thread( ()-> b.runTest() ).start();
System.out.println("waiting");
Thread.sleep(100);
System.out.println("finished");
}
public static void main(String[] args) throws Exception {
new SyncTest().check();
}
}
This example, if runTest
was synchronized on the outer object, the thread couldn't run until the check
method finished.在这个例子中,如果runTest
在外部 object 上同步,则线程无法运行,直到check
方法完成。 It is actually synchronized on the instance of the inner class though.它实际上是在内部 class 的实例上同步的。
This is a race condition to see when "running" gets printed.这是一个竞争条件,用于查看何时打印“running”。 It could be first, or after "waiting", and rarely ever but possibly after "finished".它可能是第一个,也可能是在“等待”之后,很少有但可能是在“完成”之后。
We can modify our 'runTest' program to be synchronized on the outter instance.我们可以修改我们的“runTest”程序以在外部实例上同步。
synchronized( SyncTest.this ){
System.out.println("running");
}
Now "running" will always be printed last because it has to wait for the 'check' method to finish since they're synchronized on the same object.现在“正在运行”将始终最后打印,因为它必须等待“检查”方法完成,因为它们在同一个 object 上同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.