I want to know which is the best way to stop a thread in Android. I know I can use AsyncTask
instead of it and that there is a cancel()
method. I have to use Thread
s in my situation. Here is how I'm using Thread
:
Runnable runnable = new Runnable() { @Override public void run() { //doing some work } }; new Thread(runnable).start();
So, does anyone have any idea of which is the best way to stop a thread?
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
By design, Android View objects are not thread-safe. An app is expected to create, use, and destroy UI objects, all on the main thread. If you try to modify or even reference a UI object in a thread other than the main thread, the result can be exceptions, silent failures, crashes, and other undefined misbehavior.
Thread. stop is being deprecated because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.)
Assuming that rt is a Thread , just check rt. isAlive() . Alternatively, just use a boolean flag and set it to true right before you start your thread.
You should make your thread support interrupts. Basically, you can call yourThread.interrupt()
to stop the thread and, in your run() method you'd need to periodically check the status of Thread.interrupted()
There is a good tutorial here.
This situation isn't in any way different from the standard Java. You can use the standard way to stop a thread:
class WorkerThread extends Thread { volatile boolean running = true; public void run() { // Do work... if (!running) return; //Continue doing the work } }
The main idea is to check the value of the field from time to time. When you need to stop your thread, you set running
to false. Also, as Chris has pointed out, you can use the interruption mechanism.
By the way, when you use AsyncTask, your apporach won't differ much. The only difference is that you will have to call isCancel()
method from your task instead of having a special field. If you call cancel(true)
, but don't implement this mechanism, the thread still won't stop by itself, it will run to the end.
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