+-
java – 外部和内部类方法之间的锁定和同步?
我的问题是,如果我有一些像以下代码 – :

public class OuterClass{
   public class InnerClass{
          public synchronized methodA(){ /* does something */}
   }
}

现在当多个线程想要调用内部类方法时,它们将获取外部类对象或内部类对象的锁定,以及如何修改语句以便我同步访问外部类对象/

最佳答案

when multiple threads want to call the inner class method will they acquire a lock for the outer class object

没有.

or for the inner class object

是.

and how does one modify the statement so that I synchronize access to the outer class object/

加:

synchronized (OuterClass.this)
{
}

在方法内部,但请注意,在外部锁定之前获取内部锁定,正如语法现在应该建议的那样.一致的锁定顺序对于防止死锁至关重要.您可能更喜欢先获取外部锁,在这种情况下,您应该这样做:

public void methodA()
{
    synchronized(OuterClass.this)
    {
        synchronized (this)
        {
            // ...
        }
    }
}

没有方法本身的同步声明.或者,如果您只想要外锁,请执行以下操作:

public void methodA()
{
    synchronized(OuterClass.this)
    {
        // ...
    }
}
点击查看更多相关文章

转载注明原文:java – 外部和内部类方法之间的锁定和同步? - 乐贴网