多线程死锁分析

编写下面代码,用于演示死锁情况:

public   class   ThreadDeadlock {
       public   static   void   main(String[] args)   throws   InterruptedException {
            Object obj1 =   new   Object();
            Object obj2 =   new   Object();
            Object obj3 =   new   Object();
            
            Thread t1 =   new   Thread(   new   SyncThread(obj1, obj2),   "t1" );
        Thread t2 =   new   Thread(   new   SyncThread(obj2, obj3),   "t2" );
        Thread t3 =   new   Thread(   new   SyncThread(obj3, obj1),   "t3" );
 
        t1.start();
        Thread.sleep(5000);
        t2.start();
        Thread.sleep(5000);
        t3.start();
      }
}
class   SyncThread   implements   Runnable {
       private   Object   obj1 ;
       private   Object   obj2 ;

       public   SyncThread(Object obj1, Object obj2) {
               this .   obj1   = obj1;
               this .   obj2   = obj2;
      }
       @Override
       public   void   run() {
            String name = Thread. currentThread().getName();
            System.   out .println(name +   "申请锁:" + obj1   );
               synchronized   (   obj1 ) {
                  System.   out .println(name +   "获取锁:" + obj1   );
                  work();
                  System.   out .println(name +   "申请锁:" + obj2   );
                     synchronized   (   obj2 ) {
                        System.   out .println(name +   "获取锁:" + obj2   );
                        work();
                  }
                  System.   out .println(name +   "释放锁:" + obj2   );
            }
            System.   out .println(name +   "释放锁:" + obj1   );
            System.   out .println(name +   "运行结束" );
      }
      
       private   void   work(){
               try   {
                  Thread. sleep(30000);
            }   catch   (InterruptedException e) {
                  e.printStackTrace();
            }
      }
}

执行上面的程序时,就产生了输出,但是程序却因为死锁无法停止
t1申请锁:java.lang.Object@1d87b360
t1获取锁:java.lang.Object@1d87b360
t2申请锁:java.lang.Object@47bb2cb
t2获取锁:java.lang.Object@47bb2cb
t3申请锁:java.lang.Object@653e4653
t3获取锁:java.lang.Object@653e4653
t1申请锁:java.lang.Object@47bb2cb
t2申请锁:java.lang.Object@653e4653
t3申请锁:java.lang.Object@1d87b360

要分析线程执行情况,需要用工具 dump 线程信息。可以使用   VisualVM  (http://visualvm.java.net/)
运行 VisualVM,直接右键就可以Dump
多线程死锁分析
多线程死锁分析

如果在linux 上 可以用jdk 提供 jstack 工具:
ps -eaf|grep java    找到PID
jstack 26444 >> ~/a.dump

参考文章:
http://www.importnew.com/9668.html
http://www.journaldev.com/1053/how-to-generate-thread-dump-in-java


你可能感兴趣的:(java,多线程)