按名称获取线程

Nul*_*ter 25 java multithreading android

我有一个多线程应用程序,我通过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;
}
Run Code Online (Sandbox Code Playgroud)

上面的函数检查所有正在运行的线程,然后从正在运行的线程集中返回所需的线程.也许我想要的线程被中断,然后上面的功能将无法工作.有关如何整合该功能的任何想法?

par*_*fal 23

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

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

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

  • 就我而言,我使用它来编写单元测试来调试具有可疑线程安全问题的线程。有问题的线程实现了 Runnable,但问题是:替代答案是什么?如何通过名称获取特定的 Runnable? (2认同)

Vic*_*cVu 22

Pete的答案的迭代..

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


Pet*_* B. 6

我最喜欢HashMap的想法,但如果你想保留Set,你可以迭代Set,而不是通过转换为数组的设置:

Iterator<Thread> i = threadSet.iterator();
while(i.hasNext()) {
  Thread t = i.next();
  if(t.getName().equals(threadName)) return t;
}
return null;
Run Code Online (Sandbox Code Playgroud)

  • 如上例所示,如果线程被中断,则无效! (2认同)