线程常用的两个有效停止的方法

建议使用异常法,catch中可以将异常向上抛出,使得线程停止的事件可以传播

1.return 法

public class Mythread extends Thread{
      public void run(){
           while(true){
               if(this.isInterrupted()){
                    //TO-DO ; 
                    return;
                }
                //TO-DO;
           }
      }
}

public class returnMain{
     public static void main(String[] args) throws InterruptException{
           Mythread mt = new Mythread();
           mt.start();
           Thread.sleep(1000);
           mt.interrput();
      }
}

2.异常法

public class Mythread extends Thread{
      public void run(){
         try{
           while(true){
               if(this.isInterrupted()){
                    //TO-DO; 
                    throw new InterruptException();
                }
                //TO-DO;
           }
         }catch(InterruptException e){
            //TO-DO;
         }
      }
}

public class returnMain{
     public static void main(String[] args) throws InterruptException{
           Mythread mt = new Mythread();
           mt.start();
           Thread.sleep(1000);
           mt.interrput();
      }
}

猜你喜欢

转载自blog.csdn.net/bighacker/article/details/82968317