通过ID获取线程 [英] Get a thread by Id
本文介绍了通过ID获取线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在JMX Java中工作,并且使用接口ThreadMXBean
的getAllThreadIds ()
方法获取了所有线程ID,但是我需要一种杀死给定ID的线程的方法.
I worked in JMX java and I get all the thread IDs by using the getAllThreadIds ()
method of the interface ThreadMXBean
but I need a way to kill the thread of a given ID.
例如:
ThreadMXBean tbean;
tbean = ManagementFactory.getThreadMXBean();
long[] IDs=tbean.getAllThreadIds();
//.... I need a way to kill the Threads which have this IDs
推荐答案
您可以尝试以下操作:
public void printAllThreadIds() {
Thread currentThread = Thread.currentThread();
ThreadGroup threadGroup = getRootThreadGroup(currentThread);
int allActiveThreads = threadGroup.activeCount();
Thread[] allThreads = new Thread[allActiveThreads];
threadGroup.enumerate(allThreads);
for (int i = 0; i < allThreads.length; i++) {
Thread thread = allThreads[i];
long id = thread.getId();
System.out.println(id);
}
}
private static ThreadGroup getRootThreadGroup(Thread thread) {
ThreadGroup rootGroup = thread.getThreadGroup();
while (true) {
ThreadGroup parentGroup = rootGroup.getParent();
if (parentGroup == null) {
break;
}
rootGroup = parentGroup;
}
return rootGroup;
}
但是您应该打扰Thread
而不是stop
.
But you should interrupt a Thread
and not stop
it.
不推荐使用Thread.stop()
方法,因为它会立即杀死Thread
.因此,当前由Thread
更改的数据结构可能保持不一致状态.中断使线程有机会正常关闭.
The Thread.stop()
method is deprecated, because it immediately kills a Thread
. Thus data structures that are currently changed by this Thread
might remain in a inconsistent state. The interrupt gives the Thread the chance to shutdown gracefully.
这篇关于通过ID获取线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文