java 从其 ID 获取对线程对象的引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6667496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:52:02  来源:igfitidea点击:

Get reference to Thread Object from its ID

javaandroidmultithreading

提问by SamRowley

How can I get reference to a Running Thread if I know the ID associated with that Thread?

如果我知道与该线程关联的 ID,我如何获得对该线程的引用?

e.g.

例如

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

采纳答案by bestsss

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

你有 2 种方法来做到这一点。两者都很简单:

  • 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)...

  • 旧方法:获取您可以Thread.currentThread().getGroup()在循环中访问..getParent()的根线程组。并打电话enumerate(Thread[])

  • 较新(虽然较慢)。 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.

第一种方法有一个小问题,由于 中的错误ThreadGroup.destroy(),ThreadGroup 可能根本不会枚举任何内容。

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

但是,第二个速度较慢并且存在安全漏洞。

回答by Muhammed Shakir Misarwala

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());
}