How To End threads elegantly in Android java
The thread object is a one-time consumable. Generally, after the thread executes the run method, the thread ends normally. After the thread ends, it is decommissioned. You cannot start it again. You can only create one thread object. But sometimes the run method will never end. For example, you can use a thread in a program to perform Socket listening requests or other tasks that need to be processed cyclically. In this case, these tasks are generally placed in a loop, such as a while loop. How do I exit a thread when it needs to end?
There are three methods to end the thread:
1. Use the exit flag to make the thread exit normally, that is, when the run method is complete, the thread stops.
2. Use the interrupt () method to interrupt the thread
3. Use the stop method to forcibly terminate the thread (not recommended, unexpected results may occur)
The first two methods can achieve normal thread exit, that is, the elegant end thread. The other 3rd methods are equivalent to power-off and shutdown on the computer, which is not safe.
1Use Exit flag to terminate the thread
Use a variable to control the loop. For example, the most direct method is to set a boolean flag, and set this flag to true or false to control whether the while 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 sign. When exit is true, the while LOOP exits. The default value of exit is false. when defining exit, a Java keyword volatile is used to synchronize exit. That is to say, only one thread can modify the exit value at the same time,
2UseInterrupt ()Method termination thread
The interrupt () method can be used for two terminal threads:
The thread is in the blocking status. For example, when sleep is used, wait of synchronization locks, socket's handler er, accept, and other methods are used, the thread will be in the blocking status. When the thread's interrupt () method is called, The system throws an InterruptedException exception. The Code captures the exception and then the break jumps out of the loop State to terminate the thread normally. Generally, many people think that as long as the interrupt method is called, the thread will end. In fact, it is wrong. It is necessary to capture the InterruptedException exception first and then jump out of the loop through break before the run method can be normally ended.
Public class ThreadSafe extends Thread {public void run () {while (true) {try {Thread. sleep (5*1000); blocks 5 wonderful} catch (InterruptedException e) {e. printStackTrace (); break; // after an exception is caught, run the break to exit the loop. }}}}
The thread is not blocked. isInterrupted () is used to determine the thread interruption mark to exit the loop. When the interrupt () method is used, the interrupt mark is set to true, it is the same as using a custom flag to control loops.
public class ThreadSafe extends Thread { public void run() { while (!isInterrupted()){ //do something, but no tthrow InterruptedException } } }
The reason is that interrupt () occurs only when InterruptedException exception is thrown, the interrupted () function is also called to obtain the status in which the interrupt state is true. After the call, the interrupt state is reset to false. Therefore, the isInterrupted () function is used to throw an exception () the thread cannot exit the loop because it cannot obtain the true interrupt status. Therefore, when the thread does not enter the blocked code segment, you can use isInterrupted () to determine whether the interrupt occurs to control the loop, after entering the blocking status, capture exceptions to exit the loop. Therefore, the best way to exit the thread using interrupt () is to consider either of the following situations:
Public class ThreadSafe extends Thread {public void run () {while (! IsInterrupted () {// exit try {Thread by judging the interrupt mark during non-blocking process. sleep (5*1000); // capture interrupt exceptions during blocking to exit} catch (InterruptedException e) {e. printStackTrace (); break; // after an exception is caught, run the break to exit the loop. }}}}
3UseStopMethod termination thread
Thread can be directly used in the program. stop () to forcibly terminate the thread, but the stop method is very dangerous, just as suddenly shut down the computer power, rather than shutting down the machine according to the normal program, may produce unexpected results, unsafe: thread. after the stop () call, the thread that creates the sub-thread will throw the ThreadDeatherror error and release all the locks held by the sub-thread. Generally, any code block that is locked is used to protect data consistency. after stopping (), all locks held by the thread are suddenly released (uncontrollable), so the protected data may be inconsistent, other threads may cause some strange application errors when using the corrupted data. Therefore, the stop method is not recommended to terminate the thread.