一个程序在运行的时候,如何知道它是否发生死锁,如果发生死锁,如何找到发生死锁的位置?
死锁的表现一般是线程BLOCKED
查看线程的StackTrace 就能解决死锁的问题
用jdk自带的工具 在%JAVA_HOME%\bin下的virtualVM 或是 vmConsole 都可以
点击线程进去 然后就能查看是否有死锁了
ThreadPrint.jsp打印线程信息的页面
<%@ page contentType="text/html; encoding=gb2312"%><%@ page import="java.lang.management.*"%><%
ThreadMXBean tm = ManagementFactory.getThreadMXBean();
tm.setThreadContentionMonitoringEnabled(true);
%>
<b>Thread Count: </b><%=tm.getThreadCount()%><br>
<b>Started Thread Count: </b><%=tm.getTotalStartedThreadCount()%><br>
<b>thread contention monitoring is enabled? </b><%=tm.isThreadContentionMonitoringEnabled()%><br>
<b>if the Java virtual machine supports thread contention monitoring? </b><%=tm.isThreadContentionMonitoringSupported()%><br>
<b>thread CPU time measurement is enabled? </b><%=tm.isThreadCpuTimeEnabled()%><br>
<b>if the Java virtual machine implementation supports CPU time measurement for any thread? </b><%=tm.isThreadCpuTimeSupported()%><br>
<hr>
<%
long [] tid = tm.getAllThreadIds();
ThreadInfo [] tia = tm.getThreadInfo(tid, Integer.MAX_VALUE);
long [][] threadArray = new long[tia.length][2];
for (int i = 0; i < tia.length; i++) {
long threadId = tia[i].getThreadId();
long cpuTime = tm.getThreadCpuTime(tia[i].getThreadId())/(1000*1000*1000);
threadArray[i][0] = threadId;
threadArray[i][1] = cpuTime;
}
long [] temp = new long[2];
for (int j = 0; j < threadArray.length - 1; j ++){
for (int k = j + 1; k < threadArray.length; k++ )
if (threadArray[j][1] < threadArray[k][1]){
temp = threadArray[j];
threadArray[j] = threadArray[k];
threadArray[k] = temp;
}
}
for (int t = 0; t < threadArray.length; t ++)
{
ThreadInfo ti = tm.getThreadInfo(threadArray[t][0],Integer.MAX_VALUE);
if (ti == null) continue;
%>
<b>Thread ID: </b><%=threadArray[t][0]%><br>
<b>Thread Name: </b><%=ti.getThreadName()%><br>
<b>Thread State: </b><%=ti.getThreadState()%><br>
<b>Thread Lock Name: </b><%=ti.getLockName()%><br>
<b>Thread Lock Owner Name: </b><%=ti.getLockOwnerName()%><br>
<b>Thread CPU Time: </b><%=threadArray[t][1]%> sec<br>
<b>Stack Info: (depth:<%=ti.getStackTrace().length%>)</b><br>
<%
StackTraceElement[] stes = ti.getStackTrace();
for(int j=0; j<stes.length; j++)
{
StackTraceElement ste = stes[j];
%>
+<%=ste%><br>
<%
}
%>
<hr>
<%
}
%>