Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Best and safe way to stop thread

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 Threads 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?

like image 546
Android-Droid Avatar asked Dec 14 '11 14:12

Android-Droid


People also ask

What is the preferred 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.

Is Android thread safe?

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.

Why thread stop is deprecated?

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.)

How do I know if an Android thread is running?

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.


2 Answers

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.

like image 75
Chris Avatar answered Nov 15 '22 15:11

Chris


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.

like image 39
Malcolm Avatar answered Nov 15 '22 14:11

Malcolm