How to stop the thread right

1. Introduce the principle:

Use interrupt to notify, rather than mandatory .

In Java, the best way to stop the thread is using the interrupt Interrupt, but this is just the thread will be notified to be terminated "You should stop running" and terminated the thread itself the power to decide (to decide whether and when to stop), depending on the stop request to stop the party and the party to comply with a convention good coding specification.

Start tasks and threads easily. Most of the time, we will let them run until the junction east, or let them stop on their own. However, sometimes we want to advance knot east tasks or threads, perhaps because the user canceled the operation or service to be shut down quickly, or run out or wrong. For tasks and threads can safely, quickly and reliably stopped, is not an easy task. Java does not provide any mechanism to safely terminate the thread. But it provides an interrupt (Interruption This is a coordination mechanism enables a thread to terminate the current work of another thread).

This collaborative approach is necessary, and we rarely want a task, thread or stop the service immediately, because it would immediately stop sharing data structures in an inconsistent state. Instead, you can use a collaborative task in the preparation and service: When you need to stop, they will first clear the work currently being performed, and then the end. This provides greater flexibility, because the task of code than the code itself issued a cancellation request more clearly how to perform cleanup work.

End of Life (End-of-Lifecycle) will make the task of issues, as well as service design and implementation of programs such as the process becomes complicated and this is very important but often overlooked element in the program design. One major difference between the good behavior of the software shipped with the reluctance of software is that software can be very well-behaved perfectly treatment failures, shutdown and cancellation process.


 

2, how to stop a thread right

  •   Thread ordinary circumstances usually stop in what circumstances.
    • After executing all of the code
    • There uncaught exception.

 


 

3, using several case interrupt stopping.

  • The most common situation
/ ** 
 * @data 2019/11/9 - 8:07 pm 
 * Description: The method does not run when the sleep or wait method, thread stop 
 * / 
public  class RightWayStopThreadWithoutSleep the implements the Runnable { 
    @Override 
    public  void run () {
         int NUM = 0 ;
         the while (! NUM <= Integer.MAX_VALUE / 2 && . Thread.currentThread () isInterrupted ()) {
             IF (NUM% 10000 == 0 ) 
                System.out.println (NUM + "is multiples of 10000" ); 
            NUM ++ ; 
        } 
        System.out.println ( "job completed" ); 
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadWithoutSleep());
        thread.start();
        thread.sleep(1000);
        thread.interrupt();
    }
}
  • When a thread encounters a stop blocking the thread
/ ** 
 * @data 2019/11/9 - 8:07 pm 
 * Description: The method with sleep interrupted thread 
 * / 
public  class RightWayStopThreadWithSleep {
     public  static  void main (String [] args) throws InterruptedException { 
        the Runnable Runnable = ( ) -> {
             int NUM = 0 ;
             the try {
                 the while (! NUM <= 300 && . Thread.currentThread () isInterrupted ()) {
                     IF (100% NUM == 0 ) 
                        System.out.println (NUM + "100 multiples " ); 

                    NUM ++;
                }
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
}
Results: 
0 100 is a multiple of 100 is a multiple of 100. 200 is a multiple of 100. 300 is a multiple of 100 java.lang.InterruptedException: SLEEP interrupted AT java.base
/ java.lang.Thread.sleep (Native Method,) AT threadcoreknowledge.stopthreads $ $ main .RightWayStopThreadWithSleep.lambda 0 (RightWayStopThreadWithSleep.java:18 ) AT java.base /java.lang.Thread.run(Thread.java:844)

Some methods sleep, wait and so the thread is blocked, when the thread notified interrupt, these methods deal with the notification method is to throw InterruptedException exception.

  • If the threads are blocked after each iteration
/ ** 
 * @data 2019/11/10 - 9:13 am 
 * Description: If during each execution, each loop method calls such as sleep or wait, you do not need to check whether each iteration It has been interrupted. 
 * / 
Public  class RightWayStopTHreadWithSleepEveryLoop {
     public  static  void main (String [] args) throws InterruptedException { 
        the Runnable Runnable = () -> {
             int NUM = 0 ;
             the try {
                 the while (NUM <= 10000 ) {
                     IF (100% NUM == 0 ) 
                        System.out.println (NUM + "is a multiple of 100" ); 
                    the Thread.sleep (10);
                    num++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(5000);
        thread.interrupt();
    }
}

 

 In the cycle, cpu running speed, most of the time stayed in a method of blocking it, so no need to check that each iteration has been interrupted - (Thread.currentThread () isInterrupted ().)


 

4, while if put inside try / catch, lead to interruption failure

 
 
/ ** 
* @data 2019/11/10 - 9:24 am
* Description: If while inside with try / catch, will lead to failure interrupts
* /
public class CantInterrupt {
public static void main (String [] args) throws InterruptedException {
Runnable = the Runnable () -> {
int NUM = 0;
the while {(NUM <10000 && Thread.currentThread () isInterrupted ()!.)
IF (100% NUM == 0) {
System.out.println (NUM + "100 multiples ");
}
NUM ++;
the try {
the Thread.sleep (10);
} the catch (InterruptedException E) {
e.printStackTrace ();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
Thread.sleep(5000);
thread.interrupt();
}
}
 

 

result:

0 is a multiple of 100 to 
100 is a multiple of 100 to 
200 is a multiple of 100 to 
300 is a multiple of 100 to 
400 is a multiple of 100 
java.lang.InterruptedException: SLEEP interrupted 
    AT java.base / java.lang.Thread.sleep (Native Method,) 
    AT $ $ main threadcoreknowledge.stopthreads.CantInterrupt.lambda 0 (CantInterrupt.java:17 ) 
    AT java.base /java.lang.Thread.run(Thread.java:844 ) 
500 is a multiple of 100 to 
600 is a multiple of 100 to 
700 100 multiple

 

Even if the check has been added interrupted, but an exception is thrown after the program while still inside the content execution, because when sleep, wait, etc. function block a thread, the thread will be the blocking flag is cleared, which leads to even notice terminal signal to the thread, the thread can not be detected


 

5, the actual preferred method, developing processing terminal:

/ ** 
 * @data 2019/11/10 - 9:41 am 
 * Description: Best Practices: catch the InterruptedExcetion only preferences: thrown in the method signature 
 * then the run () will be forced to try / catch 
 * / 
public  class RightWayStopTHreadInProd the implements the Runnable { 

    @Override 
    public  void RUN () {
         the while ( to true ) {
             the try { 
                System.out.println ( "Go" ); 
                throwInMethod (); 
            } the catch (InterruptedException E) { 
                e.printStackTrace () ; 
            } 
        } 
    } 

    Private void throwInMethod() throws InterruptedException {
        Thread.sleep(2000);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopTHreadInProd());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

 

the reason:

Preference on the method throws an exception.

Numeral throws Interruptedexception your way, without using capture ty exception statement block, so may be passed to the exception to the top, so that the run method can catch exceptions, for example:

Because in the run method can not throw checked Exception (only use try catch), the top-level method must handle the exception, avoid compliance with the case of missing or be swallowed, and enhancing the robustness of the code.

 

Guess you like

Origin www.cnblogs.com/zitai/p/11828998.html