1

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?

Mosam Mehta
  • 1,658
  • 6
  • 25
  • 34

3 Answers3

1

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?

salyh
  • 2,095
  • 1
  • 17
  • 31
0

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.

Community
  • 1
  • 1
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
0

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.

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • the enumerate(Thread[]) API is tricky, see https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/ThreadUtils.java – salyh Oct 09 '15 at 12:19
  • @salyh Yeah, that's why I like your `ThreadUtils` suggestion better :) – Thomas Oct 09 '15 at 12:35