I want to stop threads by using a boolean field. I have implemented some code to do this which is as follows:
My thread class is like this:
public class ParserThread implements Runnable {
private volatile boolean stopped = false;
public void stopTheThread() {
stopped = true;
}
:
:
}
And below is the main thread that starts 10 threads from the function start()
public class Main() {
Thread [] threads;
public void start() {
for(int i = 0; i < 10; i++) {
threads[i] = new Thread(new ParserThread());
}
}
public void stop() {
// code to stop all the threads
}
}
Now I want to call the stop method of the ParserThread to set "stopped = true" to stop the thread. I want this thing to be done for all the 10 threads.
How can I call that stop method. I want it to be done in the stopAllThreads() method of the Main class.
Take a look at the Executor framework. If you use an ExecutorService you can submit all your work as Runnables. The executor framework will keep track of all these threads, and all the managed threads will receive a shutdown request (interupt) via the shutdownNow() method.
Your threads will have to handle the interrupt properly. See this article for more information.
It's generally easier using the Executor framework to manage sets of threads, collect results, handle exceptions etc.
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