打印当前java程序的线程堆栈,包括线程状态,名字,监视器
打印当前java程序的线程堆栈
ThreadMXBean bean = ManagementFactory.getThreadMXBean(); Map < Thread, StackTraceElement[] > traceMap = Thread.getAllStackTraces(); Set < Thread > allThreads = traceMap.keySet(); for (Thread thread: allThreads) { StringBuilder msg = new StringBuilder(); long tid = thread.getId(); ThreadInfo threadInfo = bean.getThreadInfo(tid); if(threadInfo == null){ continue; } String lockInfo = threadInfo.getLockName() == null ? " " : ", " + threadInfo.getLockName(); msg.append("thread id: " + tid + ", name: " + threadInfo.getThreadName() + ", " + threadInfo.getThreadState() + lockInfo).append("/n"); StackTraceElement[] stackTraces = thread.getStackTrace(); for (StackTraceElement stackTrace: stackTraces) { msg.append("/t").append(stackTrace).append("/n"); } System.out.println(msg); }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10412.html