外部和内部类方法之间的锁定和同步? [英] Locking and synchronization between outer and inner class methods?

查看:457
本文介绍了外部和内部类方法之间的锁定和同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如果我有一些代码,如下: -

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

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

解决方案


当多个线程想调用内部类方法时,对于外部类对象


否。


或内部类对象


可以。


,以及如何修改语句,以便同步对外部类对象的访问/


p>

 同步(OuterClass.this)
{
}

,但是注意内部锁是在外部锁之前获取的,因为语法应该建议。一致的锁定顺序是防止死锁的关键。你可能更喜欢先获取外锁,在这种情况下你应该这样做:

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

而不使用同步对方法本身。或者如果您只需要外部锁,请执行以下操作:

  public void methodA $ b {
synchronized(OuterClass.this)
{
// ...
}
}
pre>

My question is if I have some code like the following -:

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

now 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/

解决方案

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

No.

or for the inner class object

Yes.

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

Add:

synchronized (OuterClass.this)
{
}

inside the method, but note that the inner lock is acquired before the outer lock, as the syntax should now suggest. A consistent locking order is essential to prevent deadlocks. You might prefer to acquire the outer lock first, in which case you should do this:

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

without a synchronized declaration on the method itself. Or if you only want the outer lock, do this:

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

这篇关于外部和内部类方法之间的锁定和同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆