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 to stop it.
How can i get that?
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 to stop it.
How can i get that?
To find a thread you use this: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ThreadUtils.html (https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/ThreadUtils.java)
But that gives you only a reference to the thread and you cannot simply terminate it (stop() is deprecated). Depending on what the Thread is doing maybe interrupting it is an option?
I assume you are trying to get to the thread (by its name) to call Thread.stop()
on it. If that is the case - don't do that. The method is deprecated - see why.
This question has some suggestions on how to properly stop a thread.
If you really want to access a thread by name and you don't have a reference that can be used, you could use ThreadGroup
and search the tree formed by groups and threads for the one with the correct name.
From the JavaDoc:
A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.
Thus you should be able to call Thread.currentThread().getThreadGroup()
, use getParent()
to find the initial/root group, list all active threads using enumerate(Thread[])
and search the threads.