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

这段代码有什么有关问题么?为什么不可以实现死锁

2012-08-15 
这段代码有什么问题么?为什么不可以实现死锁public classTestDeadLock implements Runnable{Object o1 n

这段代码有什么问题么?为什么不可以实现死锁
public class TestDeadLock implements Runnable
{
Object o1 = new Object();
Object o2 = new Object();
public int flag = 1;


public void run(){
System.out.println("flag="+ flag);
if(flag == 1){
synchronized(o1){
try{
Thread.sleep(500);
}catch(Exception e){}
}
synchronized(o2){
System.out.println("0");
}
}
if(flag == 0){
synchronized(o2){
try{
Thread.sleep(500);
}catch(Exception e){}
}
synchronized(o1){
System.out.println("1");
}

}

}

public static void main(String[] args) 
{
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
//new Thread(td1).start();
//new Thread(td2).start();
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}


[解决办法]
我试了下,把

Java code
synchronized(o2){System.out.println("0");} 

热点排行