下面你这段程序中,Object不用static 修饰时不会产生死锁,加上static就会产生死锁,为什么会这样呢?
public class TestDeadLock implements Runnable{
static Object o1 = new Object(); //在Object前面加static与不加对synchronized有什么影响,为什么执行结果不一样
static Object o2 = new Object(); //synchronized参数都可以是什么
public int flag = 0;
public static void main(String[] args){
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag=1;
td2.flag=0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
public void run(){
System.out.println("flag="+flag);
if(flag==0){
synchronized(o1){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
synchronized(o2){
System.out.println("hello");
}
}
}
if(flag==1){
synchronized(o2){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
synchronized(o1){
System.out.println("ok");
}
}
}
}
}