Java多线程 while内try/catch 导致自动清除中断信号

文章目录

      • while内try/catch 导致自动清除中断信号

while内try/catch 导致自动清除中断信号

示例代码如下
while循环内部, 进行了Thread.sleep(10)的try catch

public class CantInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            while ( num <= 10000) {
                if (num % 100 == 0) {
                    System.out.println(num + " 是100的整数");
                }
                num++;
                //每一次循环,休眠10ms
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        //启动线程
        Thread thread = new Thread(runnable);
        thread.start();

        //此处的  Thread.sleep(5000); 是休眠主线程, 让子线程运行5s,
        //子线程运行5s后, 给出子线程的休眠信号
        Thread.sleep(5000);
        thread.interrupt();
    }
}

程序运行如下 .
说明了即使发出了中断的信号, 抛出了异常, 但是程序依然会继续运行, 说明中断失败.
Java多线程 while内try/catch 导致自动清除中断信号_第1张图片
即使是在while 的判断中,加上线程状态的判断, 也不会成功的进行线程的中断.
Java多线程 while内try/catch 导致自动清除中断信号_第2张图片
主要的原因是 while循环内的这段try catch代码, 会把线程中断的状态位给清除掉了

    try {
       Thread.sleep(10);
         } catch (InterruptedException e) {
             e.printStackTrace();
 }

你可能感兴趣的:(Java多线程基础与核心)