【问题标题】:why doesnt thread.sleep stop at the first catch?为什么 thread.sleep 在第一次捕获时不停止?
【发布时间】:2016-11-23 21:03:11
【问题描述】:
public static void main(String s[])
{
    Thread t=Thread.currentThread();
    t.setName("main");
    try
    {
        for(int i=0;i<=5;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);//interrupted exception(System provides error on its own) 
        }
    }
    catch(InterruptedException e)
    {
        System.out.println("main thread interrupted");
    }
}

`据我了解,当出现异常情况时,控件会转到 catch,实现它并离开代码。当我们使用 thread.sleep 并为 interruptedException 创建一个 catch 时,为什么它会继续运行?而不是退出。这是代码,当 for 循环第一次运行时,它会在遇到 thread.sleep 时打印“0”,因此会出现中断异常,它不应该去捕获并执行 S.O.P 并终止吗?

【问题讨论】:

  • 嗯...您是否触发了导致sleep 终止的异常?
  • 如果你不告诉它,你为什么会认为它会终止?

标签: java interrupted-exception interruption


【解决方案1】:

为什么它一直在运行?

除非您告诉它,否则您的程序不会终止。它通常会继续运行。触发异常不会改变这一点。

【讨论】:

    【解决方案2】:

    仅调用 Thread.sleep 不会触发 InterruptedException。要让这段代码抛出 InterruptedException,必须在线程上调用中断。把代码改成

    public class MainInterruptingItself {
    
        public static void main(String s[]) {
            Thread.currentThread().interrupt();
            try {
                for(int i=0;i<=5;i++) {
                    System.out.println(i);
                    Thread.sleep(1000);
                }
            }
            catch(InterruptedException e) {
                    System.out.println("main thread interrupted");
            }
        }
    }
    

    它会打印出来

    0
    main thread interrupted
    

    这里发生的是调用中断在线程上设置中断标志。当 Thread.sleep 执行时,它会看到设置了中断标志,并基于此引发 InterruptedException。

    【讨论】:

      猜你喜欢
      • 2019-09-26
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2022-01-16
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多