如何获取线程的堆栈跟踪 [英] How to get stack trace of a thread

查看:132
本文介绍了如何获取线程的堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程应用程序.几条消息将发送到应用程序,并在单独的线程中进行处理.为此,我使用包java.util.concurrent中的ThreadPoolExecutor类和FutureTask类.

I have a multithreaded application. Several messages are coming to the application and are processed in separated threads. For this I am using classes ThreadPoolExecutor and FutureTask from package java.util.concurrent.

有时我在应用程序中遇到一些僵局.发生死锁时,我想中断阻塞线程,并希望记录该线程的堆栈跟踪,以便以后可以解决死锁.

Occasionally I have some deadlocks in the application. When a deadlock occurs I want to interrupt the blocking thread and I want to log the stack trace of this thread so that I can later resolve the deadlock.

有什么方法可以在Java中找到该线程之外的线程的堆栈跟踪吗?

Is there any way how can we find the stack trace of a thread outside of that thread in Java?

推荐答案

您可以不时(或在终止进程之前)从应用程序中记录所有线程的堆栈跟踪.为此,请使用:

You could log the stack traces of all thread from time to time (or before killing the process) from within your application. To do that use:

Map<Thread, StackTraceElement[]> m = Thread.getAllStackTraces();
for(Map.Entry<Thread,  StackTraceElement[]> e : m.entrySet()) {
    log(e.getKey().toString());
    for (StackTraceElement s : e.getValue()) {
        log("  " + s);
    }
}

运行夜间自动测试时,有时其中一些测试用例陷入僵局.我添加了一个"TimeBomb"守护程序线程,该线程等待30分钟,然后如上记录所有堆栈跟踪.

When running nightly automated tests, sometimes some one of the test cases gets into a deadlock. I added a "TimeBomb" daemon thread that waits 30 minutes, and if then logs all stack traces as above.

这篇关于如何获取线程的堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆