Reputation: 215
I have a Java class called "CreateThread" which creates one thread, everytime an object is instantiated(i.e. this upper level thread is created in the constructor). This one thread in turn creates three other threads. I can create 'N' number of objects. At the first level 'N' number of threads are created. I also name this upper level as threads as "one", "two", "three" etc. These 'N' threads created N*3 number of threads. This scenario I am able to implement. However the problem arises when I need to kill/interrupt the threads.
For example, Thread named "one" created three other threads 'a','b' and 'c'. If I want to kill all the above 4 threads(one,a,b,and c), the problem arises. I have no clue how this could be achieved.
The call to kill a thread comes from another class called "KillThread". Since I do not have a handle to any of the threads created above, I am unable to kill the threads. What I mean is that I want to kill all 4 threads from a different class which doesn't have a reference to the threads.
Help in solving the above scenario is greatly appreciated.
Thanks, Rajath
Upvotes: 1
Views: 890
Reputation: 11184
You can either store the references (the cleaner solution).
Or if you share a ThreadGroup you can hack around like this:
// Find the root thread group
ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
while (root.getParent() != null) {
root = root.getParent();
}
// Visit each thread group
visit(root, 0);
// This method recursively visits all thread groups under `group'.
public static void visit(ThreadGroup group, int level) {
// Get threads in `group'
int numThreads = group.activeCount();
Thread[] threads = new Thread[numThreads*2];
numThreads = group.enumerate(threads, false);
// Enumerate each thread in `group'
for (int i=0; i<numThreads; i++) {
// Get thread
Thread thread = threads[i];
}
// Get thread subgroups of `group'
int numGroups = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[numGroups*2];
numGroups = group.enumerate(groups, false);
// Recursively visit each subgroup
for (int i=0; i<numGroups; i++) {
visit(groups[i], level+1);
}
}
And if you can identify the threads (By thread name for example) you can kill them. I strongly recommend the first solution of just storing the references in a globally referenced tree structure.
Upvotes: 0
Reputation: 533620
To kill a thread you have to get a handle to it.
A simple way of doing this is to have an ExecutorService which you add tasks to which acts as a thread pool. To interrupt all the threads in the pool you can call executorService.shutdown();
and all the running threads will be interrupted.
Upvotes: 2
Reputation: 691865
Just store the references to the created threads somewhere. The main class could maintain a list for the N threads, and each N thread could maintain a reference to the a, b and c threads it creates.
Upvotes: 1