How to gracefully end a thread in Android Java

Source: Internet
Author: User
Tags volatile

the thread object is a disposable consumable, and the general thread finishes executingRunmethod, the thread ends normally, the thread ends and it is scrapped and cannot beStart, you can only create a new thread object. But sometimesRunthe method is never finished. For example, using threads in a program toSocketlisten for requests, or other tasks that need to be processed in a loop. In this case, it is common to place these tasks in a loop, such as whileloops. How do you exit a thread when you need to end a thread?

There are three ways to end a thread:

1. Use the exit flag to cause the thread to exit normally, that is, the thread terminates when the run method completes

2. use the interrupt () method to break the thread

3. use the stop method to forcibly terminate a thread (deprecated, unpredictable results may occur)

The first two methods can achieve the normal exit of the thread, that is, to talk about the graceful end of the thread; 3 method is the same as the computer power off shutdown, is unsafe method.


1 terminating a thread with an exit flag

Use a variable to control the loop, For example the most straightforward way is to set up a boolean true false while whether the loop exits. The code is as follows:

public class ThreadSafe extends Thread {public    volatile Boolean exit = false;         public void Run () {while         (!exit) {            //do something        }    

defines an exit flagExit, whenExitto betruewhen the whileLoop exit,ExitThe default value isfalse.in the definitionExitused aJavaKey Wordsvolatile, the purpose of this keyword is to makeExitsynchronization, meaning that only one thread can modify it at the same timeExitthe value,


2 Use Interrupt () method to terminate a thread

Use Interrupt () methods to terminal threads can be divided into two situations :

  1. The thread is in a blocked state, such as using theSleep, sync-Lockwait, Socketof thereceiver,AcceptWhen you wait for a method, the thread will be in a blocked state. When the calling thread'sInterrupt ()method, the system throws ainterruptedexceptionexception, in code by catching the exception, and then Breakjumps out of the loop state so that the thread ends normally. Often many people think that just callInterruptThe method thread ends and is actually wrong, so be sure to first captureinterruptedexceptionafter the exception is passed Breakto jump out of the loop in order to end normally .Runmethod.

public class ThreadSafe extends Thread {public void run () {while (true) {try{Thread.Sleep (5                    *1000); Blocking 5 wonderful}catch (Interruptedexception e) {e.printstacktrace ();                After the break;//catches the exception, the break jumps out of the loop. }        }    } } 
    1. the thread is not in a blocked state, using the isinterrupted () determines the thread's interrupt flag to exit the loop when using the Interrupt () method, the interrupt flag is placed true , and using a custom flag to control the loop is the same thing.

public class ThreadSafe extends Thread {public    void run () {         !isinterrupted ()} {            //do something, but No Tthrow interruptedexception        }}}    

Why is it necessary to differentiate between a blocking state and a non-blocking state, because when the blocking state isInterrupt ()occurs, the system will not only throwinterruptedexceptionexception, it also calls theinterrupted () function, the call can get to the interrupt state istrueafter the call is completed, the interrupt state is reset tofalse, so the exception is thrown after passingisinterrupted ()is not getting the interrupt state istrue, so you cannot exit the loop, so the thread does not enter a blocked code segmentisinterrupted ()To determine whether the interrupt occurred to control the loop, and to exit the loop by catching the exception after entering the blocking state. So useInterrupt ()The best way to exit a thread should be considered in both cases:

public class ThreadSafe extends Thread {public    void run () {         while (!isinterrupted ()) {//non-blocking process by judging the interrupt flag to exit            try{                Thread.Sleep (5*1000);//The blocking process captures an interrupt exception to exit            }catch (interruptedexception e) {                e.printstacktrace ();                After the break;//catches the exception, the break jumps out of the loop.            }        }    

3 Use Stop method to terminate a thread

The program can be used directlythread.stop ()to forcibly terminate the thread, butStopmethod is very dangerous, just like suddenly shut down the computer power, and not as normal program shutdown, may produce unpredictable results, unsafe mainly:thread.stop ()after the call, the thread that created the child thread throwsThreaddeatherrorand frees all locks held by the child thread. In general, any block of code that is locked is intended to protect the consistency of the data if it is calledthread.stop ()causes the sudden release of all locks held by the thread.(not controllable), the protected data can be inconsistent, and other threads can cause some strange application errors when they use the corrupted data. Therefore, it is not recommended to useStopmethod to terminate the thread.


How to gracefully end a thread in Android Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.