Java tutorial
//package com.java2s; //License from project: Apache License import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; public class Main { public static String dumpThreads() { StringBuilder sb = new StringBuilder(); ThreadMXBean bean = ManagementFactory.getThreadMXBean(); long[] ids = bean.getAllThreadIds(); _printThreads(bean, ids, sb); long[] deadlocks = bean.findDeadlockedThreads(); if (deadlocks != null && deadlocks.length > 0) { sb.append("deadlocked threads:\n"); _printThreads(bean, deadlocks, sb); } deadlocks = bean.findMonitorDeadlockedThreads(); if (deadlocks != null && deadlocks.length > 0) { sb.append("monitor deadlocked threads:\n"); _printThreads(bean, deadlocks, sb); } return sb.toString(); } protected static void _printThreads(ThreadMXBean bean, long[] ids, StringBuilder sb) { ThreadInfo[] threads = bean.getThreadInfo(ids, 20); for (ThreadInfo info : threads) { if (info == null) continue; sb.append(info.getThreadName()).append(":\n"); StackTraceElement[] stack_trace = info.getStackTrace(); for (StackTraceElement el : stack_trace) { sb.append(" at ").append(el.getClassName()).append(".").append(el.getMethodName()); sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")"); sb.append("\n"); } sb.append("\n\n"); } } }