2015-08-27 14 views
3

我正在运行一个导致死锁的简单程序。使用Jconsole分析死锁

final String resource1 = "santanu"; 
    final String resource2 = "sahoo"; 
    System.out.println(Integer.toHexString(resource1.hashCode()) ); 
    System.out.println(Integer.toHexString(resource2.hashCode())); 

    Thread t1 = new Thread(){ 

     public void run() 
     { 
      synchronized (resource1) { 
       System.out.println("Thread 1: locked resource 1"); 
       try { 

        Thread.sleep(200); 

       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       synchronized (resource2) { 
        System.out.println("Thread 1: locked resource 2");  
       }    
      } 
     } 
    }; 
    Thread t2 = new Thread(){ 
     public void run() 
     { 
      synchronized (resource2) { 
       try { 
        System.out.println("Thread 2: locked resource 2"); 
        Thread.sleep(200); 
       } catch (InterruptedException e) { 
              e.printStackTrace(); 
       } 
       synchronized (resource1) { 
        System.out.println("Thread 2: locked resource 1"); 
       } 
      } 
     } 
    }; 

    t1.start(); 
    t2.start(); 

下面是预期的输出

6f3700d4  
6823b3a   
Thread 1: locked resource 1 
Thread 2: locked resource 2 

现在我解雇JPS命令,发现PID为这个java程序,并使用jconsole <pid>命令查看僵局。

下面是JConsole的

Name: Thread-1 
State: BLOCKED on [email protected] owned by: Thread-0 
Total blocked: 1 Total waited: 1 

Stack trace: 
com.cmc.santanusol$2.run(santanusol.java:49) 
    - locked [email protected] 

现在我的问题是堆栈跟踪为什么JConsole的堆栈跟踪显示不同对象的十六进制串(java.lang.String中@)比较,我在头两个系统输出打印值?

更确切地说,为什么6f3700d4和6823b3a值没有出现在jconsole输出中?

回答

1

问题是该字符串重写hashCode。使用

System.out.println(Integer.toHexString(System.identityHashCode(resource1))); 
System.out.println(Integer.toHexString(System.identityHashCode(resource2))); 

用于调试。

背景:Object返回

getClass().getName() + "@" + Integer.toHexString(hashCode()); 
中的toString

,但字符串和其他类覆盖的toString(用绳子将不会在这方面有帮助),因此JConsole的显示信息,因为这将被证明原始的Object.toString。

+0

好的。得到它了。我发现https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#hashCode()和https://stackoverflow.com/questions/299304/why-does-javas- hashcode-in-string-use-31-as-a-multiplier来研究更多。谢谢回复。 –