线程的停止和中断

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20009015/article/details/89449749

线程停止有四种种情况:
1.run运行结束
2.异常退出
3.stop强制中止,这个不推荐使用,存在风险,比如说扫尾清理工作未完成,关闭资源未完成 就退出了。
4.interrupt方法中断线程, 需要主动编码配合,写中断逻辑,但是可控。

调用interrupt()方法只是打了个退出标志,并非真正的退出,退出逻辑需要自己写。

package ThreadCheat1.interrupt;

/**
 * @ClassName InterruptDemo
 * @Author laixiaoxing
 * @Date 2019/4/22 下午12:35
 * @Description 验证中断
 * @Version 1.0
 */
public class InterruptDemo {

   static class Mythread implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i <500000 ; i++) {
                System.out.println("i="+(i+1));
            }
        }
    }


    public static void main(String[] args) {

        Mythread mythread=new Mythread();
        Thread thread=new Thread(mythread);
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
    }

}


输出结果:
在这里插入图片描述

说明调用interrupt时候并未退出.

Thread中提供了两个方法
1.this.interrupted 测试当前线程是否中断(如果是中断,则会清除中断的状态标志,也就是如果中断了线程,第一次调用这个方法返回true,第二次继续调用则返回false)
2.this.isInterrupted 测试线程是否已经中断(不清除中断的状态标志)

可以手动编码,在线程代码逻辑里面去用interrupted判断,如果中断了,就执行中断逻辑。
一般来说,用抛出一个中断异常的处理比较好一些,因为抛出异常之后,这个线程肯定就中止了,然后外部业务代码捕获中断异常之后,进行自己想要的处理。

package ThreadCheat1.interrupt;

/**
 * @ClassName InterruptDemo
 * @Author laixiaoxing
 * @Date 2019/4/22 下午12:35
 * @Description 验证中断
 * @Version 1.0
 */
public class InterruptDemo {

    static class Mythread implements Runnable {
        @Override
        public void run() {
            try {
                for (int i = 0; i < 500000; i++) {
                    if (Thread.interrupted()) {
                        System.out.println("检测到中断状态");
                        throw new InterruptedException();
                    }
                    System.out.println("i=" + (i + 1));
                }

                System.out.println("其他处理逻辑,中断后不执行");
            } catch (InterruptedException e) {
                System.out.println("捕获到中断异常之后");
                e.printStackTrace();
            }
            }
        }


        public static void main(String[] args) {

            Mythread mythread = new Mythread();
            Thread thread = new Thread(mythread);
            thread.start();
            try {
                Thread.sleep(2000);
                thread.interrupt();//中断
            } catch (InterruptedException e) {
                System.out.println("main catch");
                e.printStackTrace();
            }
        }

    }

在这里插入图片描述

不使用stop 而是使用intterupt和 intterupted去主动配合中断,使线程中断更加可控。

猜你喜欢

转载自blog.csdn.net/qq_20009015/article/details/89449749