Java example of a way to end a run and stop a thread by sharing a variable

  • 2020-04-01 02:32:34
  • OfStack

The stop() method has been deprecated because it is not safe. The detailed explanation is given in the API documentation.
The thread is interrupted by the interrupted () method. Is not recommended.
The thread is stopped by ending the run () method by sharing a variable. If the instance


public class ThreadInterrupt {
    public static void main(String []args){
        Runner run = new Runner();
        run.start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block

        }

        //run.stop();// The method has been abandoned, is not recommended to use, too rough 
        //run.interrupt(); // Throws an exception, but writing business in exception handling is obviously not appropriate and is not recommended 
        run.flag=false;//Recommended method to stop threads
    }
}
class  Runner extends Thread{
    boolean flag = true;
    public void run(){
    /*    while(true){
            System.out.println(new Date()+"----");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                System.out.println("Interrupted");
                return;
            }
        }
        */

        while(flag){
            System.out.println(new Date()+"----");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                System.out.println("Interrupted");
                return;
            }
        }
    }
}


Related articles: