当调用一个对象的非静态的synchronized方法时,锁定的是对象本身;
当调用一个对象的静态的synchronized方法时,锁定的是对象所属的类的class对象(在方法区中)
示例如下:
package cn.edu.tju;
public class JvmLockTest {
public static void main(String[] args) {
MyClass myClass = new MyClass();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
myClass.func1();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
myClass.func2();
}
});
t1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
class MyClass {
public synchronized void func1(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("in func1......");
}
public static synchronized void func2(){
System.out.println("in func2......");
}
}
输出: