public void dumpThreadDump() { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) { System.out.println(ti.toString()); } }
-------------------------- 上面这个打不全,因为ThreadInfo的toString方法里面,写死了最多打印8行堆栈。
复制,去掉8行的限制就行了。
public String dumpThreadDump() { StringBuilder s = new StringBuilder(); ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true, Integer.MAX_VALUE)) { s.append(threadToString(ti)); if (ti.getStackTrace().length > 8) {
} } return s.toString(); }
public String threadToString(ThreadInfo t) { StringBuilder sb = new StringBuilder("\"" + t.getThreadName() + "\"" + (t.isDaemon() ? " daemon" : "") + " prio=" + t.getPriority() + " Id=" + t.getThreadId() + " " + t.getThreadState()); if (t.getLockName() != null) { sb.append(" on " + t.getLockName()); } if (t.getLockOwnerName() != null) { sb.append(" owned by \"" + t.getLockOwnerName() + "\" Id=" + t.getLockOwnerId()); } if (t.isSuspended()) { sb.append(" (suspended)"); } if (t.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); int i = 0; for (; i < t.getStackTrace().length; i++) { StackTraceElement ste = t.getStackTrace()[i]; sb.append("\tat " + ste.toString()); sb.append('\n'); if (i == 0 && t.getLockInfo() != null) { Thread.State ts = t.getThreadState(); switch (ts) { case BLOCKED: sb.append("\t- blocked on " + t.getLockInfo()); sb.append('\n'); break; case WAITING: sb.append("\t- waiting on " + t.getLockInfo()); sb.append('\n'); break; case TIMED_WAITING: sb.append("\t- waiting on " + t.getLockInfo()); sb.append('\n'); break; default: } }
for (MonitorInfo mi : t.getLockedMonitors()) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked " + mi); sb.append('\n'); } } }
LockInfo[] locks = t.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = " + locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- " + li); sb.append('\n'); } } sb.append('\n'); return sb.toString(); }
|