使用 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.