gpt4 book ai didi

java - 获取带有线程上下文的堆栈跟踪

转载 作者:行者123 更新时间:2023-11-30 09:23:50 26 4
gpt4 key购买 nike

我正在尝试获取 Java 中线程的当前堆栈跟踪。我探索了以下方法:

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

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

是否还有其他方法可以更有效地获取 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

最佳答案

Is there any other approach also by which we can get current stack trace of thread in Java that is more efficient?

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

要补充的一点是,如果你想获取线程的堆栈跟踪但你不确定你是否会使用它,保存异常然后只调用 getStackTrace()< 应该会更高效 在需要的时候。在调用之前,堆栈跟踪不会在 Exception 中完全充实。有关详细信息,请参阅 Throwable.getOurStackTrace() 的代码。

关于java - 获取带有线程上下文的堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15892744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com