How would you interrupt or stop a thread when you're given just the thread id? Say, the thread id is of format long.
-
[This](http://stackoverflow.com/questions/7786305/stopping-a-specific-java-thread) may be helpful. – Akshay Sep 04 '14 at 01:31
2 Answers
Start with Thread.enumerate and Thread.activeCount
Thread findThreadById(long id) {
Thread [] threads = new Thread[Thread.activeCount() * 2];
int count = Thread.enumerate(threads);
for (int i = 0; i < count; i++) {
if (threads[i].getId() == id) {
return threads[i];
}
}
return null;
}
The doubling of Thread.activeCount() above is to catch the cases where the number of threads increased between the call to Thread.activeCount and Thread.enumerate. It may or may not be needed, but shouldn't cost much other than a few bytes of memory.
So not that you have the Thread instance that you want, just call Thread.interrupt.
Note - that hard stopping and termination of a thread is bad form. Finding ways to have the thread exit on its own based on some sort of condition (set by another thread) is much better.

- 100,020
- 15
- 103
- 173
With the thread's cooperation, using any method it offers. Without the thread's cooperation, you cannot. Interrupting or stopping a thread without its cooperation destroys the process. (Say the thread held a lock that another thread needs or broke an invariant that it was about to restore.)
This question tends to come from a poor way of thinking about threads and processes. Threads cooperate to get work done. Any time you feel like you need to "reach in" to a thread from the outside to "make" it do the right thing, that should be a warning that you coded the thread wrong in the first place. Code the thread to do what, and only what, you want it to do. Then you won't have to interrupt or stop it.
If for some reason that's not possible, then design into that thread's code the capability to interrupt or stop it.

- 179,497
- 17
- 214
- 278