我有一个多线程应用程序,我通过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;
}
上面的函数检查所有正在运行的线程,然后从正在运行的线程集中返回所需的线程。也许我想要的线程被中断,然后上面的功能将无法工作。有关如何整合该功能的任何想法?
答案 0 :(得分:22)
您可以使用ThreadGroup找到所有活动主题:
ThreadGroup.getParent()
直到线程组层次结构为止,直到找到具有空父级的组。ThreadGroup.enumerate()
查找系统上的所有线程。这样做的价值完全逃脱了我......你可以用命名线程做什么?除非你在实现Thread
(这是一个草率的编程开始)时继承Runnable
。
答案 1 :(得分:20)
Pete的回答迭代..
public Thread getThreadByName(String threadName) {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().equals(threadName)) return t;
}
return null;
}
答案 2 :(得分: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;
答案 3 :(得分:0)
这就是我在this:
的基础上做到的/*
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;
}