如何正确的中断线程?你的姿势是否正确

Java停止线程的逻辑(协同、通知)

在Java程序中,我们想要停止一个线程可以通过interrupt方法进行停止。但是当我们调用interrupt方法之后,它可能并不会立刻就会停止线程,而是通知线程需要停止。线程接收到通知之后会根据自身的情况判断是否需要停止,它可能会立即停止,也有可能会执行一段时间后停止,也可能根本就不停止。

那么Java为什么要选择这种非强制性的线程中断呢?其实更多是为了数据安全,保证程序的健壮性。因为我们不知道程序正在做什么事情。如果贸然停止,可能会造成数据的错乱、不完整。

一个简单的例子

public class _24_ThreadTest implements Runnable {

    @Override
    public void run() {
        int count = 0;
        while (!Thread.currentThread().isInterrupted() && count <= 2000) {
            System.out.println("count: " + count++);
        }
    }

    public static void main(String[] args) throws Exception {
        _24_ThreadTest threadTest = new _24_ThreadTest();
        Thread thread = new Thread(threadTest);
        thread.start();
        Thread.sleep(10);
        // 中断线程
        thread.interrupt();
    }
}
复制代码

这个例子是一个简单的通过interrupt中断线程的案例,run方法中通过判断当前线程是否中断,并且count是否大于2000来进行循环。如果线程中断则退出循环,线程执行结束。这种就属于线程正常停止的情况。

Sleep是否会收到线程中断信号

public class _24_ThreadTest implements Runnable {

    @Override
    public void run() {
        int count = 0;
        while (!Thread.currentThread().isInterrupted() && count <= 2000) {
            try {
                System.out.println("count: " + count++);
                // 子线程睡眠
                Thread.sleep(1000 * 2);
                System.out.println("方法体:" + Thread.currentThread().isInterrupted());
            } catch (InterruptedException e) {
                System.out.println("异常:" + Thread.currentThread().isInterrupted());
                // 线程中断标志位被重置为false
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        _24_ThreadTest threadTest = new _24_ThreadTest();
        Thread thread = new Thread(threadTest);
        thread.start();
        Thread.sleep(10);
        // 中断线程
        thread.interrupt();
    }
}
复制代码

如果在子线程中睡眠中,主线程通过interrupt方法进行中断,那么子线程还能不能收到中断信号。其实在这种情况下线程也是可以接收到信号通知的,这个时候会抛出InterruptedException,并且将线程中断标志位设置为false。

在抛出异常后,线程标志位被设置为false,那么在下次循环判断count没有为false的情况下,还是可以进入循环体的。这个时候线程就无法停止。

执行结果:

案例场景

在进行一些后台任务通过线程跑的时候,如果在循环中遇到线程中断异常,我们需要终止当前任务,并且告诉客户端当前任务执行失败的是哪条记录,这种情况下就可以通过异常中再次中断的方式来停止线程,并且可以返回给客户端当前出现异常的记录是哪条。而不会是接着执行下去。

解决方法

public class _24_ThreadTest implements Runnable {

    @Override
    public void run() {
        int count = 0;
        while (!Thread.currentThread().isInterrupted() && count <= 2000) {
            try {
                System.out.println("count: " + count++);
                // 子线程睡眠
                Thread.sleep(1000 * 2);
                Thread.currentThread().interrupt();
                System.out.println("方法体:" + Thread.currentThread().isInterrupted());
            } catch (InterruptedException e) {
                // 再次中断
                Thread.currentThread().interrupt();
                System.out.println("异常:" + Thread.currentThread().isInterrupted());
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        _24_ThreadTest threadTest = new _24_ThreadTest();
        Thread thread = new Thread(threadTest);
        thread.start();
        Thread.sleep(10);
        // 中断线程
        thread.interrupt();
    }
}
复制代码

既然我们已经知道,在出现线程中断异常之后线程中断标志位会被重置为false,那么我们可以在异常中手动的再次中断当前线程,那么就可以完全停止线程任务。

总结

上面我们简单介绍了如何正确的停止线程,如果在以后的面试中被问到这类问题,那么你是不是可以流畅的回答面试官了。

在run方法中遇到异常,我们是不能直接生吞的,一定要做处理,你可以是简单的日志记录,也可以中断线程。但就是不能不做任何处理。

其实还有其他的一些方法来停止线程,比如stop(),这类方法已被舍弃,这种强制停止可能会引起线程的数据安全问题,所以已经不再推荐使用了。

猜你喜欢

转载自juejin.im/post/7131897496241963015