开发者

Get reference to Thread Object from its ID

开发者 https://www.devze.com 2023-03-19 13:01 出处:网络
How c开发者_运维技巧an I get reference to a Running Thread if I know the ID associated with that Thread?

How c开发者_运维技巧an I get reference to a Running Thread if I know the ID associated with that Thread?

e.g.

long threadID = 12342;
Thread thread = (What goes here?) getThreadFromId(threadID); //I know this is totally made up


You have 2 ways to do it. Both are quite simple:

  • Old way: get the root thread group you may access Thread.currentThread().getGroup()..getParent() in loop. and call enumerate(Thread[])

  • newer (slower though). for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getId()==id)...

The first method has a small problem that due to a bug in ThreadGroup.destroy(), a ThreadGroup may not enumerate anything at all.

The second is slower and has a security flaw, though.


You can use following code in order to get the Thread Name (For e.g. I want to get names of Threads that are in deadlock )

ThreadMXBean threadMB = ManagementFactory.getThreadMXBean();
long threadIds[] = threadMB.findDeadlockedThreads();
for (long id : threadIds) {
     System.out.println("The deadLock Thread id is : " + id
                            + "  > "
                            +       
     threadMB.getThreadInfo(id).getThreadName());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消