日期:2014-05-20  浏览次数:20645 次

这段代码有什么问题么?为什么不可以实现死锁
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");
}