死锁问题,求助。在线等
我看了视屏自己写了下让线程死锁的代码,是这样的下面这样的,如果我把static Object o1 = new Object() ;static Object o2 = new Object() ;2个new出来的对象前面的static 去掉的话就不会死锁了,不知道什么原因 求助
public class TestDeadLock implements Runnable {
public int flag = 1 ;
static Object o1 = new Object() ;
static Object o2 = new Object() ;
public void run() {
System.out.println("flag="+flag) ;
if(flag == 1) {
synchronized(o1) {
try{
Thread.sleep(500) ;
}catch(InterruptedException e) {
e.printStackTrace() ;
}
synchronized(o2) {
System.out.println("1") ;
}
}
}
if(flag == 2) {
synchronized(o2) {
try {
Thread.sleep(500) ;
}catch(InterruptedException e) {
e.printStackTrace() ;
}
synchronized(o1) {
System.out.println("2") ;
}
}
}
}
public static void main(String[] args) {
TestDeadLock test1 = new TestDeadLock() ;
TestDeadLock test2 = new TestDeadLock() ;
test1.flag = 1 ;
test2.flag = 2 ;
Thread t1 = new Thread(test1) ;
Thread t2 = new Thread(test2) ;
t1.start() ;
t2.start() ;
}
}