如何安全的终止线程

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

在这里插入图片描述

导读
在日常开发中,我们如何终止一个线程,才是安全的?

一.线程中断机制介绍

JAVA中有3种方式可以终止正在运行的线程

①线程正常退出,即run()方法执行完毕了

②使用Thread类中的stop()方法强行终止线程。但stop()方法已经过期了,不推荐使用

③使用中断机制

那么,为什么stop()方法不推荐使用?
因为stop()方法在终结一个线程时不会保证线程的资源正常释放,通常是没有给予线程完成资源释放工作的机会,
因此会导致程序可能工作在不确定状态下。

二.演示如何安全终止线程

在《java并发编程艺术》一书中,作者为我们提供了两种安全终止线程的方法,下面我们来看看:

ublic class Shutdown {

    public static void main(String[] args) throws Exception {
        Runner one = new Runner();
        Thread countThread = new Thread(one, "CountThread");
        countThread.start();
        // 睡眠1秒,main线程对CountThread进行中断,使CountThread能够感知中断而结束
        TimeUnit.SECONDS.sleep(1);
        countThread.interrupt();
        Runner two = new Runner();
        countThread = new Thread(two, "CountThread");
        countThread.start();
        // 睡眠1秒,main线程对Runner two进行取消,使CountThread能够感知on为false而结束
        TimeUnit.SECONDS.sleep(1);
        two.cancel();
    }
    private static class Runner implements Runnable {
        private long i;
        private volatile boolean on = true;
        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()){
                i++;
            }
            System.out.println("Count i = " + i);
        }
        public void cancel() {
            on = false;
        }
    }
}

示例在执行过程中,main线程通过中断操作(interrupt()方法)和cancel()方法均可使CountThread得以终止。这种通过标识位或者中断操作的方式能够使线程在终止时有机会去清理资源,而不是武断地将线程停止,因此这种终止线程的做法显得更加安全和优雅。

三.总结

通过上面的测试,我们总结了两种安全终止线程的方法:
1.中断操作方式-interrupt()
2.自定义标识位

返回专栏目录

猜你喜欢

转载自blog.csdn.net/Milogenius/article/details/89578338