如果安全的中断线程

如果安全的中断线程

   package ch1.base.safeend;
   
   //如果安全的中断线程
   public class EndThread {
       private static class UseThread extends Thread{
           public UseThread(String name){
               super(name);
           }
   
       public void run(){
           String name =Thread.currentThread().getName();
           System.out.println(name+" interrupt flat ="+isInterrupted());
           while(!isInterrupted()){
               System.out.println(name+" is running...");
               System.out.println(name+" inner interrupt flag ="+isInterrupted());
           }

           System.out.println(name+" interrupt flag="+interrupted());
       }
   }

   public static void main(String[] args)throws InterruptedException {

       Thread endTread = new UseThread("endThread");
       endTread.start();
       Thread.sleep(1);
       endTread.interrupt();//中断线程,其实就是设置线程的标识位true
   }

   /**
    输出类似:
    endThread interrupt flat =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =false
    endThread is running...
    endThread inner interrupt flag =true
    endThread interrupt flag=true

    Process finished with exit code 0

    */
 }

你可能感兴趣的:(如果安全的中断线程)