使用 Java 中的 dumpStack() 方法的目的是什麼?


dumpStack() 方法是 Thread 類的靜態方法,它可以用來列印或顯示當前執行緒的堆疊跟蹤到 System.err 中。dumpStack() 方法的目的主要是除錯,在內部,此方法呼叫 Throwable 類的 printStackTrace() 方法。此方法不會引發任何異常。

語法

public static void dumpStack()

示例

public class ThreadDumpStackTest {
   public static void main(String args[]) {
      Thread t = Thread.currentThread();
      t.setName("ThreadDumpStackTest");
      t.setPriority(1);
      System.out.println("Current Thread: " + t);
      int count = Thread.activeCount();
      System.out.println("Active threads: " + count);
      Thread threads[] = new Thread[count];
      Thread.enumerate(threads);
      for (int i = 0; i < count; i++) {
         System.out.println(i + ": " + threads[i]);
      }
      Thread.dumpStack();
   }
}

輸出

Current Thread: Thread[#1,ThreadDumpStackTest,1,main]
Active threads: 1
0: Thread[#1,ThreadDumpStackTest,1,main]
java.lang.Exception: Stack trace
	at java.base/java.lang.Thread.dumpStack(Thread.java:2282)
	at ThreadDumpStackTest.main(ThreadDumpStackTest.java:14) 

更新時間: 2023 年 12 月 01 日

571 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.