按名称获取线程
2022-09-01 14:03:25
我有一个多线程应用程序,我为每个线程通过属性分配一个唯一的名称。现在,我希望功能能够使用线程的相应名称直接访问线程。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;
}
上述函数检查所有正在运行的线程,然后从正在运行的线程集中返回所需的线程。也许我想要的线程被中断了,那么上面的函数将不起作用。关于如何整合该功能的任何想法?