I worked in JMX java and I get all the thread IDs by using the getAllThreadIds ()
method of the interface ThreadMXBean
but I need a way to kill the thread of a given ID.
for example:
ThreadMXBean tbean;
tbean = ManagementFactory.getThreadMXBean();
long[] IDs=tbean.getAllThreadIds();
//.... I need a way to kill the Threads which have this IDs
You can try this:
public void printAllThreadIds() {
Thread currentThread = Thread.currentThread();
ThreadGroup threadGroup = getRootThreadGroup(currentThread);
int allActiveThreads = threadGroup.activeCount();
Thread[] allThreads = new Thread[allActiveThreads];
threadGroup.enumerate(allThreads);
for (int i = 0; i < allThreads.length; i++) {
Thread thread = allThreads[i];
long id = thread.getId();
System.out.println(id);
}
}
private static ThreadGroup getRootThreadGroup(Thread thread) {
ThreadGroup currentGroup = thread.getThreadGroup();
ThreadGroup parentGroup;
while ((parentGroup = currentGroup.getParent()) != null) {
currentGroup = parentGroup;
}
return currentGroup;
}
But you should interrupt a Thread
and not stop
it.
The Thread.stop()
method is deprecated, because it immediately kills a Thread
. Thus data structures that are currently changed by this Thread
might remain in a inconsistent state. The interrupt gives the Thread the chance to shutdown gracefully.
There is actually no good way to kill a thread in java. There used be an api called Thread.stop() but it is also deperecated. Check this link for more details why Thread.stop was bad and how we should be stopping a thread.
http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
Getting just the thread id will not help you, you need to have the thread object reference to set a flag to stop that thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With