问题
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.
Somethings like the following function:
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?
回答1:
You can find all active threads using ThreadGroup:
- 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.
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).
回答2:
An iteration of Pete's answer..
public Thread getThreadByName(String threadName) {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().equals(threadName)) return t;
}
return null;
}
回答3:
I like the HashMap idea best, but if you want to keep the Set, you can iterate over the Set, rather than going through the setup of converting to an array:
Iterator<Thread> i = threadSet.iterator();
while(i.hasNext()) {
Thread t = i.next();
if(t.getName().equals(threadName)) return t;
}
return null;
回答4:
That's how I did it on the basis of 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/get-thread-by-name