- 打印指定線程調用棧:
/**
* 自定義打印調用棧:
* @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佔用過高時,可以打印線程方法棧信息,用於分析。
愛家人,愛生活,愛設計,愛編程,擁抱精彩人生!