【问题标题】:Java acquire monitor lock of other classJava获取其他类的监控锁
【发布时间】:2016-10-04 22:44:47
【问题描述】:

假设我有这个课程:

public class Status {
   private int x;

   // monitor lock?
   public Object myLock = new Object();

   public Status(int x) {
      this.x = x;
   }

   public int checkVar() {
      return x;
   }

   public int incrementVar() {
      ++x;
   }
}

然后我有一个这样的线程类:

public class MyThread implements Runnable {

   public void run() {
        // Is this how to acquire monitor lock of Status class?
        synchronized (statusInstance.myLock) {
          statusInstance.checkVar();
          statusInstance.incrementVar();
        }
   }    
}

你是这样获取另一个类的监视器锁的吧?

【问题讨论】:

  • 你也可以使用 synchronized (statusInstance)

标签: java multithreading concurrency locking


【解决方案1】:

Java 中,如果您有对任何对象的引用,您可以将其用作mutex。但是你会锁定对象而不是类。

问题是任何人都可以改变该对象,因为它是公共的,并获得了他们不应该获得的锁。

 statusInstance.myLock = new Object();

使用公共可变对象作为互斥体被认为是有害的。鉴于ClassLoader 中只有一个类,您可以锁定该类

 synchronized(Status.class){
    ..
 }

或者让你的锁变成静态的

public static final Object MY_LOCK = new Object();    

【讨论】:

    【解决方案2】:

    正确。您还可以通过以下方式将对象本身用作锁:

    public class MyThread implements Runnable {
    
       public void run() {
         // Is this how to acquire monitor lock of Status class?
         synchronized (statusInstance) {
           statusInstance.checkVar();
           statusInstance.incrementVar();
         }
       }    
    }
    

    这更简单,因为您不再需要声明 myLock

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多