获取带有上下文的stacktrace到线程

时间:2013-04-09 03:24:03

标签: java multithreading exception

我试图在Java中获取Thread的当前堆栈跟踪。我已经探索了以下方法:

  1. 在Java中打印当前线程堆栈跟踪的最简单方法之一是使用java.lang.Thread类中的dumpStack()方法

  2. 打印堆栈跟踪的另一种方法是使用Throwable类的printStackTrace()方法

  3. 还有其他方法可以让我们在Java中获得更高效的线程当前堆栈跟踪吗?

    以下是我设计的课程..

    public class StackTraceExample 
    { 
    private static final Logger logger = Logger.getLogger(StringReplace.class.getName()); 
    public static void main(String args[]) 
    {
     //calling a method to print stack trace further down 
    first();
    } 
    
    public static void first()
    { 
    second(); 
    }
    
     private static void second() 
     {
     third();
     } 
    
     private static void third()
     {
     //If you want to print stack trace on console than use dumpStack() method 
      System.err.println("Stack trace of current thread using dumpStack() method");
      Thread.currentThread().dumpStack(); 
    
      //This is another way to print stack trace from current method 
    
      System.err.println("Printing stack trace using printStackTrace() method of Throwable "); 
      new Throwable().printStackTrace();
    
      //If you want stack trace as StackTraceElement in program itself than 
      //use getStackTrace() method of Thread class
    
      StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    
      //Once you get StackTraceElement you can also print it to console 
      System.err.println("displaying Stack trace from StackTraceElement in Java");
      for(StackTraceElement st : stackTrace)
      {
      // System.err.println(st);
      } 
      }
      }
    

    输出: -

    Stack trace of current thread using dumpStack() method 
    java.lang.Exception: Stack trace 
    at java.lang.Thread.dumpStack(Thread.java:1249) 
    at test.StringReplace.third(StringReplace.java:38) 
    at test.StringReplace.second(StringReplace.java:31) 
    at test.StringReplace.first(StringReplace.java:27)
    at test.StringReplace.main(StringReplace.java:23)
    
    
    Printing stack trace using printStackTrace() method of Throwable 
    java.lang.Throwable
    at test.StringReplace.third(StringReplace.java:42)
     at test.StringReplace.second(StringReplace.java:31)
     at test.StringReplace.first(StringReplace.java:27)
     at test.StringReplace.main(StringReplace.java:23) 
     displaying Stack trace from StackTraceElement in Java
    

1 个答案:

答案 0 :(得分:2)

  

还有其他方法可以让我们在Java中获得更高效的线程当前堆栈跟踪吗?

没有。 thread.printStackTrace()(或getStackTrace())是正确的方法。如果它是当前线程,那么它在内部使用Exception,但如果它是另一个线程则直接生成堆栈跟踪。

要添加的一件事是,如果你想获得一个线程的堆栈跟踪,但你不确定是否会使用它,那么保存异常应该更有效率,然后只在需要时调用getStackTrace() 。在进行调用之前,堆栈跟踪未在Exception中完全填充。有关详细信息,请参阅Throwable.getOurStackTrace()的代码。