按名称获取线程

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;
}

上述函数检查所有正在运行的线程,然后从正在运行的线程集中返回所需的线程。也许我想要的线程被中断了,那么上面的函数将不起作用。关于如何整合该功能的任何想法?


答案 1

皮特答案的迭代。

public Thread getThreadByName(String threadName) {
    for (Thread t : Thread.getAllStackTraces().keySet()) {
        if (t.getName().equals(threadName)) return t;
    }
    return null;
}

答案 2

您可以使用 ThreadGroup 查找所有活动线程:

  • 获取当前话题的组
  • 通过调用来提升线程组层次结构,直到找到具有空父级的组。ThreadGroup.getParent()
  • 调用以查找系统上的所有线程。ThreadGroup.enumerate()

这样做的价值完全逃脱了我...你可能会用一个命名的线程做什么?除非你在应该实现的时候进行子类化(这是从一开始就草率的编程)。ThreadRunnable


推荐