获取线程通过名称 [英] Get Thread By Name

查看:141
本文介绍了获取线程通过名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程的应用程序,我()属性分配一个唯一的名称为每个线程通过的setName。现在,我想要的功能,直接访问该线程及其相应的名称。

I have a multithreaded application and I assign a unique name to each thread through setName() property. Now, I want functionality to get access to the threads directly with their corresponding name.

出头像以下功能:

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

上述功能检查所有正在运行的线程,然后从该组运行的线程返回所需线程。也许我的期望线程被中断,那么上述功能将无法正常工作。关于如何将这些功能的任何想法?

The above function checks all running threads and then returns the desired thread from the set of running threads. Maybe my desired thread is interrupted, then the above function won't work. Any ideas on how to incorporate that functionality?

推荐答案

您可以找到所有的有效的使用的线程组

You can find all active threads using ThreadGroup:

  • 让你的当前线程的小组
  • 在致电您的方式工作的线程组层次 ThreadGroup.getParent(),直到找到一组具有null父。
  • 呼叫 ThreadGroup.enumerate()查找系统中的所有线程。
  • Get your current thread's group
  • Work your way up the threadgroup hierarchy by calling ThreadGroup.getParent() until you find a group with a null parent.
  • Call ThreadGroup.enumerate() to find all threads on the system.

这样做完全的价值脱离了我......你会怎么可能与一个名为线程呢?除非你继承时,你应该实施的Runnable (这是草率的编程开始)。

The value of doing this completely escapes me ... what will you possibly do with a named thread? Unless you're subclassing Thread when you should be implementing Runnable (which is sloppy programming to start with).

这篇关于获取线程通过名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆