Search code examples
androidmultithreadingterminaterunnable

Android terminating a thread created through runnable


Let's say in various points in my application, I create and fire off a new runnable like so:

new Thread(new Runnable() { 
    public void run() {
    while(true) {
       //do lots of stuff
       //draw lots of stuff on screen, have a good ol time
       //total loop processing time abt 1250-1500ms
       //check for conditions to stop the loop, break;
   }    }   }

Now, is there any way to terminate that thread midway through execution other than break; inside my while loop? I'd like to be able to kill it specifically and immediately from the parent thread, like, as in the event that the user just requested to load a different map. It feels clunky to insert an if (stopFlag) break; (set in parent thread) after every 5 or so lines of code.

I peeked at Runnable's and Thread's methods and I just can't see it. Someone know an awesome trick?


Solution

  • You may use AsyncTask and call cancel to cancel the thread.