- 打印指定线程调用栈:
/**
* 自定义打印调用栈:
* @param currentThread 根据当前线程
*/
public static void printCallStatck(Thread currentThread) {
StackTraceElement[] stackElements = currentThread.getStackTrace();
if (stackElements != null) {
System.out.println("-----------------------------------");
for (int i = 0; i < stackElements.length; i++) {
System.out.print(stackElements[i].getClassName() + "--");
System.out.print(stackElements[i].getLineNumber() + "--");
System.out.println(stackElements[i].getMethodName());
}
System.out.println("-----------------------------------");
}
}
PS:可以应用于基础库方法调用分析,被哪些方法调用,是否正常调用。
举例:比如某个资源池,出现资源泄露,分析发现借用次数超过归还次数,通过上述方法可以分析出是哪些方法只借不还。
- 查看当前全体线程运行状况:
/**
* dump所有运行中线程方法栈调用信息
*/
public static void dump() {
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int threadsNum = currentGroup.activeCount();
Thread[] threads = new Thread[threadsNum];
currentGroup.enumerate(threads);
for (int i = 0; i < threadsNum; i++) {
System.out.println("thread num: " + i + " --thread name: " + threads[i].getName()+" --status: "+threads[i].getState());
printCallStatck(threads[i]);
}
}
结果:
thread num: 0 --thread name: main --status: RUNNABLE
-----------------------------------
java.lang.Thread--1556--getStackTrace
test.ThreadStackTest--27--printCallStatck
test.ThreadStackTest--18--dump
test.ThreadStackTest--5--main
-----------------------------------
PS:一般在线程池负载过高,或者系统CPU占用过高时,可以打印线程方法栈信息,用于分析。
爱家人,爱生活,爱设计,爱编程,拥抱精彩人生!