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

javaobject oriented programmingprogramming更新于 2025/6/30 12:28:17

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[ThreadDumpStackTest,1,main]
Active threads: 1
0: Thread[ThreadDumpStackTest,1,main]
java.lang.Exception: Stack trace
        at java.lang.Thread.dumpStack(Thread.java:1336)
        at ThreadDumpStackTest.main(ThreadDumpStackTest.java:14)

相关文章


有用资源