How do we terminate a Thread
or ThreadGroup
instance by it's name ?
Asked
Active
Viewed 6,502 times
0

sura2k
- 7,365
- 13
- 61
- 80
-
2What have you tried? What research have you done? SO is not your research assistent. – Gray Mar 20 '13 at 16:13
-
So us some effort that you had done to achieve this task.. – Vishal K Mar 20 '13 at 16:18
-
In my case, I have dynamic numbers of threads running in the server. So I can't keep those references. When the response serves, all of thread hooks will be gone. And using a shared variable or volatile variable to give a signal won't work I think. – sura2k Mar 20 '13 at 16:19
-
what makes you think that? – Ralf H Mar 20 '13 at 16:25
-
I can have those `Thread` references in my session. If so it will allocate some memory too. If I can use a `ThreadGroup`, and if I can stop all the threads under that `ThreadGroup` it will be much easier. But methods like stop(), suspend() etc are deprecated from the `ThreadGroup`. – sura2k Mar 20 '13 at 16:32
2 Answers
5
Something like this
Thread[] a = new Thread[1000];
int n = Thread.enumerate(a);
for (int i = 0; i < n; i++) {
if (a[i].getName().equals(name)) {
a[i].interrupt();
break;
}
}
though interrupt() does not terminate the thread, stop() does (though deprecated)

Evgeniy Dorofeev
- 133,369
- 30
- 199
- 275
-
It's important to know that interrupting a thread does not "terminate" it. See: http://stackoverflow.com/questions/10632451/does-calling-thread-interrupt-before-a-thread-join-cause-the-join-to-throw/10635005#10635005 – Gray Mar 20 '13 at 16:30
-
Interruption is the best approach, but executing code should support it correctly. – Mikhail Mar 20 '13 at 16:51
3
It depends on what do you mean when you say "terminate".
But first tip is that you have to get a list of all threads to terminate. Use Thread.getThreads()
to do this. You can filter threads by their group if needed.
Now, how to stop the thread? There are 2 ways.
- call
stop()
method. It is deprecated and you should never use it because it might cause system to enter inconsistent state. However, if you really want ... this method is still supported. - Every thread should support shutdown mechanism, i.e. a "protocol" that can be used to signal thread to exit its
run()
method. If all threads are yours you can make them to implement your own interface (e.g.Terminatable
) with methodterminate()
that will change value of flag and cause thread to exit. In this case your code that terminates threads should iterate over threads, check that thread should be terminated and that it implements interfaceTerminatable
, cast to it and call itsterminate()
method.

AlexR
- 114,158
- 16
- 130
- 208