How to terminate a thread safe?

1, waste stop () method

stop () method at the end of a thread does not guarantee normal resource release thread, the thread is usually not given the opportunity to complete the work release resources, will lead the program may work in an uncertain state .

2, by identifying bit or interrupt the operation

Import java.util.concurrent.TimeUnit; 

public  class ShutDown {
     public  static  void main (String [] args) throws InterruptedException { 
        Runner One = new new Runner (); 
        the Thread countThread = new new the Thread (One, "CountThread" ); 
        countThread.start (); 
        // sleep one second, main thread CountThread interrupt, the interrupt can be perceived CountThread ended 
        TimeUnit.SECONDS.sleep (1 ); 
        countThread.interrupt (); 
        Runner TWO = new new Runner (); 
        countThread =new new the Thread (TWO, "CountThread" ); 
        countThread.start (); 
        // sleep one second, main thread Runner two were canceled, so CountThread can be perceived as false and ending on 
        TimeUnit.SECONDS.sleep (1 ); 
        TWO. Cancel (); 
    } 

    static  class Runner the implements the Runnable {
         Private  Long I;
         Private  volatile  Boolean ON = to true ; 

        @Override 
        public  void RUN () {
             the while (! && ON . Thread.currentThread () isInterrupted ()) { 
                I ++ ;
            } 
            System.out.println ( "I = the Count" + I); 
        } 
    // identified location to false 
        public  void Cancel () { 
            ON = to false ; 
        } 
    } 
}

 

Guess you like

Origin www.cnblogs.com/Aug-20/p/11808739.html