Java获取其他类的监视器锁
假设我有一门课:Java获取其他类的监视器锁,java,multithreading,concurrency,locking,Java,Multithreading,Concurrency,Locking,假设我有一门课: 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 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();
}
}
}
这就是获取另一个类的监视器锁的方法,对吗?在Java中,如果有对任何对象的引用,可以将其用作互斥锁。但是您将锁定对象而不是类
问题是,任何人都可以对该对象进行变异,因为它是公共的,并且可以获得他们不应该获得的锁
statusInstance.myLock = new Object();
使用公共可变对象作为互斥对象被认为是有害的。如果类加载器中只有一个类,则可以锁定该类
或者让你的锁是静态的
public static final Object MY_LOCK = new Object();
对。还可以使用以下方法将对象本身用作锁:
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。您也可以使用synchronized statusInstance
public class MyThread implements Runnable {
public void run() {
// Is this how to acquire monitor lock of Status class?
synchronized (statusInstance) {
statusInstance.checkVar();
statusInstance.incrementVar();
}
}
}