首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

为何这个不是死锁啊哪里写错了

2012-09-18 
为什么这个不是死锁啊,哪里写错了public class DeadClock implements Runnable{publicint flag1private

为什么这个不是死锁啊,哪里写错了
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();就行了

热点排行