Reputation: 3564
I am working on an analytics app. in Java.At the top i have a GUI which has START and STOP Buttons.On Clicking Start i create a Thread inside whose RUN method i call an API method which internally creates a Thread.i.e.
On Clicking "START"----->a Thread is Spawned---->in this thread's RUN method i use an API cal which creates a thread Internally...
Now,what i want is that when i click the STOP GUI button,the internal thread created by the API call should also die..
How can i achieve that??
Thanks
Upvotes: 2
Views: 4219
Reputation: 114777
You'll have to implement some logic to the thread classes. First, they need some "kill switches" - you can't (shouldn't!!) stop them from outside. We usually define and set a flag on the thread instance so that it knows, when it has to terminate.
Then, we don't have a thread "hierarchy". A thread instances will need to its own list of child threads and, if it (the parent) receives the stop signal, it will have to send the same signal to its children.
public abstract class MyThread extends Thread {
private List<MyThread> children = new ArrayList<MyThread>();
private boolean stopNow = false; // <- this is the stop flag
public void stopNow() {
for (MyThread thread:children) {
thread.stopNow();
}
stopNow = true;
}
}
(This will not make a thread stop actually, we'll have to "monitor" the stopNow
flag in the run
method).
Upvotes: 2