问题描述
我怎样才能得到引用正在运行的线程,如果我知道与该主题相关的ID?
例如。
长期主题ID = 12342;
线程线程=(什么放在这里?)getThreadFromId(主题ID); //我知道这完全是由
您有2个方法可以做到这一点。两者都是相当简单:
-
老办法:让您可以访问
Thread.currentThread()根线程组getGroup()
..的getParent()的循环。和呼叫枚举(线程[])
-
新的(虽然速度较慢)。
的(线程t:Thread.getAllStackTraces()键设置())如果(t.getId()== ID)...
第一种方法有一个小问题,由于()在 ThreadGroup.destroy一个错误,一个线程组可能不枚举任何东西。
二是慢,有一个安全漏洞,虽然。
How can 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 callenumerate(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.
这篇关于获取引用其ID Thread对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!