首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >按名称获取线程

按名称获取线程
EN

Stack Overflow用户
提问于 2013-03-13 03:14:50
回答 3查看 35.7K关注 0票数 28

我有一个多线程应用程序,并通过setName()属性为每个线程分配一个惟一的名称。现在,我希望功能可以使用线程的相应名称直接访问它们。

类似于下面的函数:

代码语言:javascript
复制
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;
}

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

EN

回答 3

Stack Overflow用户

发布于 2014-12-11 09:59:22

皮特答案的一个迭代..

代码语言:javascript
复制
public Thread getThreadByName(String threadName) {
    for (Thread t : Thread.getAllStackTraces().keySet()) {
        if (t.getName().equals(threadName)) return t;
    }
    return null;
}
票数 25
EN

Stack Overflow用户

发布于 2013-03-13 03:30:23

我最喜欢HashMap的想法,但是如果你想保留这个集合,你可以遍历这个集合,而不是进行转换成数组的设置:

代码语言:javascript
复制
Iterator<Thread> i = threadSet.iterator();
while(i.hasNext()) {
  Thread t = i.next();
  if(t.getName().equals(threadName)) return t;
}
return null;
票数 6
EN

Stack Overflow用户

发布于 2018-03-12 01:57:46

这就是我在this的基础上所做的

代码语言:javascript
复制
/*
    MIGHT THROW NULL POINTER
 */
Thread getThreadByName(String name) {
    // Get current Thread Group
    ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
    ThreadGroup parentThreadGroup;
    while ((parentThreadGroup = threadGroup.getParent()) != null) {
        threadGroup = parentThreadGroup;
    }
    // List all active Threads
    final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    int nAllocated = threadMXBean.getThreadCount();
    int n = 0;
    Thread[] threads;
    do {
        nAllocated *= 2;
        threads = new Thread[nAllocated];
        n = threadGroup.enumerate(threads, true);
    } while (n == nAllocated);
    threads = Arrays.copyOf(threads, n);
    // Get Thread by name
    for (Thread thread : threads) {
        System.out.println(thread.getName());
        if (thread.getName().equals(name)) {
            return thread;
        }
    }
    return null;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15370120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档