为什么这个不是死锁啊,哪里写错了
public class DeadClock implements Runnable{
public int flag=1;
private Object o1=new Object(), o2=new Object();
public void run()
{
System.out.println("flag="+flag);
if(flag==1)
{
synchronized(o1)
{
try {
Thread.sleep(50000);
} catch (InterruptedException e) {}
synchronized(o2)
{
System.out.println(1);
}
}
}
if(flag==0)
{
synchronized(o2)
{
try {
Thread.sleep(50000);
} catch (InterruptedException e) {}
synchronized(o1)
{
System.out.println(0);
}
}
}
}
public static void main(String[] args) {
DeadClock dead1 =new DeadClock();
DeadClock dead2 =new DeadClock();
dead1.flag=1;
dead2.flag=0;
Thread t1 =new Thread(dead1);
Thread t2 =new Thread(dead2);
t1.start();
t2.start();
}
}
------解决方案--------------------
因为你的o1和o2不是静态变量,即每个对象都有自己的o1和o2
如果你要看到死锁现象,把private Object o1=new Object(), o2=new Object();改为
private static Object o1=new Object(), o2=new Object();就行了