对象锁和类锁问题实验
今天遇到了一个问题,就是当获取到类锁时还能获取到该类的对象锁吗?
实验一
都是获取类锁,显然会实现同步
public class Solution {
/*实验结果
获得类锁,睡觉zzz
起床...
获得对象锁
*/
public static void main(String[] args) {
Solution s = new Solution();
Thread t1 = new Thread(){
@Override
public void run() {
synchronized(Solution.class){
System.out.println("获得类锁,睡觉zzz");
try {
this.sleep(2000);
System.out.println("起床...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread t2 = new Thread(){
@Override
public void run() {
synchronized(Solution.class){
System.out.println("获得对象锁");
}
}
};
t1.start();
t2.start();
}
}
实验二
线程1获取类锁,线程2获取对象锁
public class Solution {
/*
实验结果:
获得类锁,睡觉zzz
获得对象锁
起床...
*/
public static void main(String[] args) {
Solution s = new Solution();
Thread t1 = new Thread(){
@Override
public void run() {
synchronized(Solution.class){
System.out.println("获得类锁,睡觉zzz");
try {
this.sleep(2000);
System.out.println("起床...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread t2 = new Thread(){
@Override
public void run() {
synchronized(s){
System.out.println("获得对象锁");
}
}
};
t1.start();
t2.start();
}
}
总结:实验结果得知,获取类锁之后还是能获取该类的对象锁的。