Eric
Eric

Reputation: 1973

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?

Upvotes: 0

Views: 3756

Answers (3)

Shawn Lauzon
Shawn Lauzon

Reputation: 6282

You could use AsyncTask as suggested, which probably works best in this case. I believe you can also use the interrupt() method, which is preferred if good if you're not in Android, but still suffers from having to explicitly check if it is interrupted:

Thread t = new Thread(new Runnable() {
    public void run() {
        while (true) {
            // do some stuff
            if (isInterrupted()) {
                break;
            }
        }
     });
t.start();

// Whoa! Need to stop that work!
t.interrupt();

Upvotes: 0

Giulio Piancastelli
Giulio Piancastelli

Reputation: 15817

Instead of while (true) you may check for a condition or a flag that would be changed properly when the Thread/Runnable should be stopped. This seems to be the suggested strategy since Thread.stop() has been deprecated.

Upvotes: 0

MByD
MByD

Reputation: 137442

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

Upvotes: 3

Related Questions