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

难道线程的死锁==线程的等待???应该不是吧
死锁没有成功,不能找出错误原因
public   class   TestDeadLock   implements   Runnable   {
  int   frag   ;
  static   Object   o1   =   new   Object(),o2   =   new   Object();
  public   void   run(){
    System.out.println( "frag "+frag);
    if(frag==1){
      synchronized(o1){
       
        try{
          Thread.sleep(500);
        }catch(InterruptedException   e){
          e.printStackTrace();
        }
      }
      synchronized(o2){
        System.out.print( "ok2 ");
      }
    }
   
   
    if(frag==0){
      synchronized(o2){
        try{
          Thread.sleep(500);
        }catch(InterruptedException   e){
          e.printStackTrace();
        }
      }
      synchronized(o1){
        System.out.print( "ok1 ");
      }
    }
  }
  public   static   void   main(String[]   args)   {
    TestDeadLock   td1   =   new   TestDeadLock();
    TestDeadLock   td2   =   new   TestDeadLock();
    td1.frag=1;
    td2.frag=0;
    Thread   th1   =   new   Thread(td1);
    Thread   th2   =   new   Thread(td2);
    th1.start();
    th2.start();
   
  }

}



------解决方案--------------------
你这段程序并不构成死锁。td1 是在释放了 o1 之后才申请 o2,而 td2 是在释放了 o2 之后才申请 o1,所以不是死锁,只是等了一会儿而已。

你如果把 td1 的 synchronized(o2) 放到 synchronized(o1) 内部,再把 td2 的 synchronized(o1) 放到 synchronized(o2) 的内部,就会死锁了。