本文介绍了获取引用其ID Thread对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到引用正在运行的线程,如果我知道与该主题相关的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 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.

这篇关于获取引用其ID Thread对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:36