我们说我有这堂课:
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();
}
}
}
这是你如何获得另一个类的监视器锁定的权利?
答案 0 :(得分:2)
在Java
中,如果您对任何对象有引用,则可以将其用作mutex
。但是你会锁定对象而不是类。
问题在于任何人都可以改变该对象,因为它是公开的,并获得了他们不应该获取的锁定。
statusInstance.myLock = new Object();
将公共可变对象用作互斥锁被认为是有害的。鉴于ClassLoader
synchronized(Status.class){
..
}
或使你的锁定为静态最终
public static final Object MY_LOCK = new Object();
答案 1 :(得分: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
。