使用外类锁获取内类锁? [英] Acquiring inner-class lock using outer-class locks?

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

问题描述

我有一个外部类A,并有一个公共的内部类,结构如下 - :

I have an outer class A and that has a public inner class, the structure is as follows -:

public class A{

      public int x;

      public class B{
        private static final int y;
      }

      public synchronized int method1(){
             return x+ B.y;
      }
}



A类也会锁定内部类的成员吗?

the question is if I used synchronized keyword on every method of the class A will it also lock the members of the inner class as well?

推荐答案


if我在类A的每个方法上使用了synchronized关键字,它还会锁定内部类的成员吗?

if I used synchronized keyword on every method of the class A will it also lock the members of the inner class as well?

您似乎在这里对某些方面感到困惑。

You seem to be confused in a number of respects here.


  • 使用原始互斥(例如通过同步方法) 只锁定在同步的其他线程

  • Using a primitive mutex (e.g. via a synchronized method) only locks against other threads that are synchronizing on the same mutex.

当您调用同步实例方法时,您获取的互斥体是 code> ...目标对象。

When you call a synchronized instance method, the mutex you are acquiring is the mutex for this ... the target object.

在您的示例中,您似乎想锁定 static 字段,而不是实例字段。

In your example, it seems that you want to lock a static field, not an instance field.

如果我正确理解你正在做什么,正确的做法是这样:

If I understand correctly what you are trying to do, the correct way to do it is something like this:

 public synchronized int method1(){
     synchronized (B.class) {
         return x + B.y;
     }
 }

注意这涉及到获取 mutexes,所以你需要确保你的代码总是以相同的顺序获取它们。 (如果你不这样做,那么就有死锁的危险。)

Note that this involves acquiring two mutexes, so you need to make sure that your code always acquires them in the same order. (If you don't, then there is a risk of deadlocks.)

如果你在<$ c上创建并调用了一个同步静态方法, $ c> B 字段的值。

这篇关于使用外类锁获取内类锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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