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();
}
}

解决方案 »

  1.   

    两个TestDeadLock对象拥有不同的o1,o2,每个线程使用各自的对象锁,所以不会出现死锁。
    楼主可以把对象o1,o2该成静态试试。这样的话,对于td1和td2,o1和o2是同一个。
    static Object o1 = new Object();
    static Object o2 = new Object();
      

  2.   

    我试了下,把
    synchronized(o2){
    System.out.println("0");
    }
    放到synchronized(o1)里面.
    这样会出现得到一个锁争用另一个的情况.
    synchronized(o1)
    {
    try
    {
    Thread.sleep(500);
    }
    catch(Exception e)
    {}
    synchronized(o2)
    {
    System.out.println("0");
    }
    }
      

  3.   

    下面的flag=0那段代码也把
    synchronized(o1){
    System.out.println("1");
    }
    放到synchronized(o2)里。
    synchronized(o2)
    {
    try
    {
    Thread.sleep(500);
    }
    catch(Exception e)
    {}
    synchronized(o1)
    {
    System.out.println("1");
    }
    }
      

  4.   

    谢谢了  hao le