多线程 - 5.线程的停止

优雅的停止线程在多线程中很关键

  • 指当前线程结束本任务的操作后,停止并收回线程,而不是暴力的直接停止线程。
  1. Thread.stop() 函数,废弃,不优雅不安全
  2. return; 与 break;,不建议,会有代码污染(不要在 try 里面写 return)
  3. 异常的方式停止多线程,推荐,不会弄脏代码,还有日志
  1. interrupt() 方法用于中断线程
  2. interrupted() 是静态方法,返回的当前线程的中断状态。如果当前线程被中断且没有抛出中断异常那么中断状态不会被清除,否则中断状态就会被清除
  3. isInterrupted() 仅仅查询中断标志位来判断是否发生中断
  1. interrupt()的缺点:interrupted() 只能停止主线程,而无法停止多线程,因为 interrupted() 首先需要标记一个停止线程的位置,然后才会停止线程
  2. interrupt(),如果此线程在调用该类的 Object class 或 join() 、 join(long) 、 sleep(long,int) 方法、wait() 、 wait(long) 或 wait(long,int) 方法时被阻止,则其中断状态将被清除,并将收到 InterruptedException
  1. 所以用异常的方式停止线程
  2. interrupt() + 手动 new 异常
  3. interrupt() + sleep()
  4. interrupt() + wait() 不要让他们相遇
class MyThread extends Thread{
    @Override
    public void run(){
        try{
            while(true){
                if(this.interrupted()){
                    System.out.println("isInterrupted:" + this.isInterrupted());
                    throw new InterruptedException();
                }
                System.out.println("不会输出");
            }
        } catch(InterruptedException exception){
            System.out.println("进入异常");
        }
    }
}

public class test0{
    public static void main(String[] args){
        Thread myThread = new MyThread();
        myThread.start();
        myThread.interrupt();
    }
}
class MyThread extends Thread{
    @Override
    public void run(){
        try{
            while(true){
                Thread.sleep(1000);
                System.out.println("不会输出");
            }
        } catch(InterruptedException exception){
            System.out.println("进入异常");
        }
    }
}

public class test1{
    public static void main(String[] args){
        Thread myThread = new MyThread();
        myThread.start();
        myThread.interrupt();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43845524/article/details/106801740