Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop all worker threads in android application

Tags:

java

android

how to stop all running worker threads in an android application without stoping the main thread?

Any example for this?

like image 291
Soosoo Avatar asked Mar 14 '12 09:03

Soosoo


People also ask

How do I stop a worker thread?

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.

How do you end a thread in Android Studio?

interrupt() method is called from main() to terminate the thread. Invoking Thread. interrupt() sets an internal interrupt status flag.

What are worker threads in Android?

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.


2 Answers

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.

like image 128
AlexR Avatar answered Nov 15 '22 22:11

AlexR


this post talks a ton about threads, please read and repost if that does not answer your question

Stopping/Destroying a Thread

like image 41
Mayank Avatar answered Nov 15 '22 23:11

Mayank