我有一个多线程应用程序,并通过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;
}
上面的函数检查所有运行的线程,然后从运行的线程集中返回所需的线程。也许我想要的线程被中断了,那么上面的函数就不起作用了。有没有关于如何合并该功能的想法?
发布于 2014-12-11 09:59:22
皮特答案的一个迭代..
public Thread getThreadByName(String threadName) {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().equals(threadName)) return t;
}
return null;
}
发布于 2013-03-13 03:30:23
我最喜欢HashMap的想法,但是如果你想保留这个集合,你可以遍历这个集合,而不是进行转换成数组的设置:
Iterator<Thread> i = threadSet.iterator();
while(i.hasNext()) {
Thread t = i.next();
if(t.getName().equals(threadName)) return t;
}
return null;
发布于 2018-03-12 01:57:46
这就是我在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;
}
https://stackoverflow.com/questions/15370120
复制相似问题