Java Thread dumpStack() 方法



描述

Java Thread dumpStack() 方法將當前執行緒的堆疊跟蹤列印到標準錯誤流。此方法僅用於除錯。

宣告

以下是java.lang.Thread.dumpStack() 方法的宣告

public static void dumpStack()

引數

返回值

此方法不返回任何值。

異常

示例:在單執行緒環境中列印執行緒堆疊跟蹤

以下示例演示了 Java Thread dumpStack() 方法的使用。在這個程式中,我們建立了一個 ThreadDemo 類。在 main 方法中,我們使用 currentThread() 方法檢索了當前執行緒,然後使用 activeCount() 方法列印了活動執行緒數。最後,我們使用 dumpStack() 方法列印了堆疊跟蹤。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      t.setName("Admin Thread");
   
      // set thread priority to 1
      t.setPriority(1);
    
      // prints the current thread
      System.out.println("Thread = " + t);
    
      int count = Thread.activeCount();
      System.out.println("currently active threads = " + count);
    
      /* prints a stack trace of the current thread to the standard
         error stream, used for debugging */
      Thread.dumpStack();
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Thread = Thread[#1,Admin Thread,1,main]
currently active threads = 1
java.lang.Exception: Stack trace
	at java.base/java.lang.Thread.dumpStack(Thread.java:2209)
	at com.tutorialspoint.ThreadDemo.main(ThreadDemo.java:21)

示例:在多執行緒環境中列印執行緒堆疊跟蹤

以下示例演示了 Java Thread dumpStack() 方法的使用。在這個程式中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadDemo。在建構函式中,我們使用 currentThread() 方法檢索了當前執行緒,然後建立了另一個執行緒並使用 start() 方法啟動它。最後,我們使用 dumpStack() 方法列印了堆疊跟蹤。在 main 方法中,建立了 ThreadDemo 類的例項。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   ThreadDemo() {
      // main thread
      Thread currThread = Thread.currentThread();
      
      // thread created
      Thread t = new Thread(this, "Admin Thread");
   
      System.out.println("current thread = " + currThread);
      System.out.println("thread created = " + t);
      
      // this will call run() function
      t.start();
	  
      /* prints a stack trace of the current thread to the standard
         error stream, used for debugging */
      Thread.dumpStack();
   }

   public void run() {
      System.out.println("This is run() method");
   }

   public static void main(String args[]) {
      new ThreadDemo();
   }
} 

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

current thread = Thread[#1,main,5,main]
thread created = Thread[#21,Admin Thread,5,main]
This is run() method
java.lang.Exception: Stack trace
	at java.base/java.lang.Thread.dumpStack(Thread.java:2209)
	at com.tutorialspoint.ThreadDemo.<init>(ThreadDemo.java:20)
	at com.tutorialspoint.ThreadDemo.main(ThreadDemo.java:28)
java_lang_thread.htm
廣告
© . All rights reserved.