停止一个线程要如何操作

179 阅读2分钟

一般来说,我们不需要手动去停止线程,都是等待线程自己停止,或者遇到特殊情况导致线程被动停止。那么我们要停止线程,要怎么才能办到?

public class TestInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()){
                    System.out.println("线程还没感应到中断信号,继续执行");
                }
                System.out.println("----线程感应到中断信号----");
            }
        });
        thread.start(); //启动线程

        Thread.sleep(1000); //休眠1000毫秒也就是1秒

        thread.interrupt(); //中断子线程

        System.out.println("线程的中断状态:" + thread.isInterrupted());
    }
}

在这里插入图片描述
在上面线程收到中断信号后没有立即中断,而是继续运行下去,直到线程内的操作执行完毕后,才关闭线程,这时候调用“ thread.isInterrupted() ”的输出是 true

  • Thread.currentThread().isInterrupted():当前线程是否已经中断?是输出 true,否输出 false
  • thread.interrupt():对线程发出中断信号,通知线程中断,但是否要中断还是要取决于线程本身(就好像街口碰到美女,美女跟你说,帅哥来玩嘛,你去不去不就随你么?不过大家都是正经人,当然是不去啦,我都不用问)

线程在睡眠中,是否能收到中断信号?

public class TestInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        System.out.println("线程还没感应到中断信号,继续执行");
                        Thread.sleep(3000);
                    }
                } catch (InterruptedException e) {
                    System.out.println("线程收到中断信号,并抛出了异常");
                    e.printStackTrace();
                }
                System.out.println("----线程感应到中断信号----");
            }
        });
        thread.start(); //启动线程

        Thread.sleep(2000); //休眠1000毫秒也就是1秒

        thread.interrupt(); //中断子线程

        System.out.println("线程的中断状态:" + thread.isInterrupted());
    }
}

在这里插入图片描述

答案是可以的,线程在sleep()中的时候,收到中断信号,是会被打断并抛出异常( InterruptedException),并清除中断信号的状态,这时候调用“ thread.isInterrupted() ” 的结果为 false


线程还有一些被丢弃的方法,可以中断线程

例如 stop() 方法,调用stop()方法,会直接把线程给停止掉,并不会通知线程说,我要停止了,你看要不要停止

public class TestInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()){
                    System.out.println("线程还没感应到中断信号,继续执行");
                }
                System.out.println("----线程感应到中断信号----");
            }
        });
        thread.start(); //启动线程

        Thread.sleep(1000); //休眠1000毫秒也就是1秒

        thread.stop(); //中断子线程

        System.out.println("线程的中断状态:" + thread.isInterrupted());
    }
}

欢迎大家关注下个人的「公众号」:独醉贪欢