在下面的代码片段中,我有一个问题。线程将获取类级别锁或对象级别锁?
private static Object lock=new Object();
private static Object lock2=new Object();
public static void m1(){
synchronized(lock){
//statements
}
}
public static void m2(){
synchronized(lock2){
//statements
}
}
每个对象都有一个“监视器”。使用同步块时,请指定要在其上同步其监视器的实例。除了同步的块,还有同步的方法。同步的[[instance方法将获取该方法在其上被调用的实例的监视器,而同步的[[static方法将获取该封闭类的java.lang.Class
对象的监视器。]public class Foo {
private static final Object STATIC_LOCK = new Object();
private final Object instanceLock = new Object();
public static void bar() {
synchronized (STATIC_LOCK) { // acquires monitor of "STATIC_LOCK" instance
// guarded code
}
}
public static synchronized void baz() { // acquires monitor of "Foo.class" instance
// guarded code
}
public void qux() {
synchronized (instanceLock) { // acquires monitor of "instanceLock" instance
// guarded code
}
}
public synchronized void quux() { // acquires monitor of "this" instance
// guarded code
}
}
public class Test {
private static Object lock2 = new Object();
public synchronized void m1() {
// Lock on current object instance(this) as this is an instance method
}
public synchronized static void m2() {
// Lock at class level as this is a static method
}
public static void m3() {
synchronized (lock2) {
// Lock on `lock2` object. It doesn't make a difference if this method
// is static or not at the time of acquiring lock on a given object here
}
}
}