Recipe Canceling a Thread

Sometimes when a component is finished or killed, the developer wants the threads it spawns to also be killed. For example, take a thread defined in an activity:

private volatile Thread myThread;

The myThread.stop() method is deprecated because it might leave the application in an unpredictable state. Instead, use the following when needed, such as in the onStop() method of the parent component:

//use to stop the thread myThread if(myThread != null) {

Thread dummy = myThread; myThread = null; dummy.interrupt();

At the application level, there is another way to do this: Declare all spawned threads as daemon threads using the setDaemon(true) method.This ensures threads associated with that application are killed when the application's main thread is killed.

//use when initially starting a thread myThread.setDaemon(true);

myThread.start();

Finally, there is always the method of using a while(stillRunning) loop in the run() method and externally setting stillRunning=false to kill the thread. However, this might not provide sufficient control over the timing of when the thread stops.

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Post a comment