我有一个多线程应用程序,我通过 setName()
属性为每个线程分配一个唯一名称。现在,我希望功能可以直接使用相应名称访问线程。
类似下面的函数:
public Thread getThreadByName(String threadName) {
Thread __tmp = null;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
for (int i = 0; i < threadArray.length; i++) {
if (threadArray[i].getName().equals(threadName))
__tmp = threadArray[i];
}
return __tmp;
}
上述函数检查所有正在运行的线程,然后从正在运行的线程集中返回所需的线程。也许我想要的线程被中断了,那么上面的函数就不起作用了。关于如何合并该功能的任何想法?
最佳答案
Pete 回答的迭代..
public Thread getThreadByName(String threadName) {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().equals(threadName)) return t;
}
return null;
}
关于java - 按名称获取线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15370120/