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

莫不是线程的死锁==线程的等待?应该不是吧

2011-11-23 
难道线程的死锁线程的等待???应该不是吧死锁没有成功,不能找出错误原因publicclassTestDeadLockimplemen

难道线程的死锁==线程的等待???应该不是吧
死锁没有成功,不能找出错误原因
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) 的内部,就会死锁了。

热点排行