这是我写的死锁代码:
package dieLock;
public class DieLock extends Thread {
private boolean flag;
private Object obj1 = new Object();
private Object obj2 = new Object();
public DieLock(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if (flag) {
synchronized (obj1) {
System.out.println("if obj1");
synchronized (obj2) {
System.out.println("if obj2");
}
}
} else {
synchronized (obj2) {
System.out.println("else obj2");
synchronized (obj1) {
System.out.println("else obj1");
}
}
}
}
}
package dieLock;
public class DieLockDemo {
public static void main(String[] args){
DieLock lock1=new DieLock(true);
DieLock lock2=new DieLock(false);
lock1.start();
lock2.start();
}
}
以上代码,如果允许DieLockDemo的话,不会出现死锁问题(反复刷新,运行了很多遍),如果将 private Object obj1 = new Object(); private Object obj2 = new Object();加上静态修饰符修饰的话,private static Object obj1 = new Object(); private staitc Object obj2 = new Object(); 就会很容易出现死锁问题,请问大神为什么会这样 加上静态和不加静态为什么差别会那么大,synchronized不是传一个任意Object锁对象就可以吗,为什么还牵扯到静态修饰的问题,请大神详细解释一下,谢谢!
|
|