how to stop all running worker threads in an android application without stoping the main thread?
Any example for this?
For a worker thread, normal thread termination is simple: Exit the controlling function and return a value that signifies the reason for termination. You can use either the AfxEndThread function or a return statement.
interrupt() method is called from main() to terminate the thread. Invoking Thread. interrupt() sets an internal interrupt status flag.
Worker threads are background threads. They are the threads that are created separately, other than the UI thread. Since blocking the UI thread is restricted according to the rule, the user should run the child processes and tasks in worker threads.
Actually thread has method stop()
, so you can go over all worker threads and call this method on each one.
The question is "where to obtain list of worker threads?" Better solution is to store this list somewhere at application level, i.e. every time you are creating worker thread put it to special list. This is better solution because you and only you know that the thread is "worker" thread.
But theoretically you can even discover your application dynamically and retrieve the threads. There is static method Thread.enumerate(Thread[] threads)
that fills provided array. But how to know how many threads are running now? Use Thread.activeCount()
.
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
for (Thread t : threads) {
if (isWorkerThread(t)) {
t.stop();
}
}
It is up to you to identify your worker threads. For example you can use the thread's name or the thread's stack trace for this.
BUT it is a crime to call deprecated method stop()
. Please refer to javadoc of this method to read about the reasons.
The "right" method is to implement graceful shutdown mechanism at application layer. Each thread should check some flag that says whether thread should shutdown and when flag is true just return from run()
method. In this case it is very simple to close your working threads: just set value of this flag to true and threads will terminate themselves. This is the "right" solution.
this post talks a ton about threads, please read and repost if that does not answer your question
Stopping/Destroying a 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