为什么我必须将每个 Thread.sleep() 调用包装在 try/catch 语句中?

新手上路,请多包涵

我正在尝试用 Java 编写我的第一个多线程程序。我不明白为什么我们需要围绕 for 循环进行异常处理。当我在没有 try/catch 子句的情况下编译时,它给出了 InterruptedException

这是消息:

 Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException

但是当使用 try/catch 运行时,catch 块中的 sysout 永远不会显示 - 这意味着无论如何都没有捕获到这样的异常!

 public class SecondThread implements Runnable {
    Thread t;

    SecondThread() {
        t = new Thread(this, "Thread 2");
        t.start();
    }

    public void run() {
        try {
            for (int i=5; i>0; i--) {
                System.out.println("thread 2: " + i);
                Thread.sleep(1000);
            }
        }
        catch (InterruptedException e) {
            System.out.println("thread 2 interrupted");
        }
    }
}

public class MainThread {

    public static void main(String[] args) {
        new SecondThread();

        try {
            for (int i=5; i>0; i--) {
                System.out.println("main thread: " + i);
                Thread.sleep(2000);
            }
        }
        catch (InterruptedException e) {
            System.out.println("main thread interrupted");
        }
    }
}

原文由 Sergio Gliesh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答

如果 Thread.sleep 方法检测到当前线程设置了中断标志,则它会抛出 InterruptedException,提前从睡眠中唤醒并允许您使用异常将控制权重新定位到当前流之外的某个地方。只有在线程上调用中断时才会设置该标志。

由于您的程序不会在任何线程上调用中断,因此在您运行该程序时不会抛出 InterruptedException。编译器仍然要求您捕获异常,因为它是在 sleep 方法上声明的已检查异常。

如果将这样的方法添加到 SecondThread

 public void cancel() {
    t.interrupt();
}

然后在main方法中调用cancel,像这样:

 public static void main(String[] args){
    SecondThread secondThread =  new SecondThread();

    try{
        for(int i=5 ; i>0 ; i--){
            System.out.println("main thread: " + i);
            Thread.sleep(2000);
            secondThread.cancel();
        }
    }
    catch(InterruptedException e){
        System.out.println("main thread interrupted");
    }
}

您将看到在 SecondThread 的运行方法中捕获 InterruptedException 的地方的 println。

编译错误显示在 eclipse 中的“问题”选项卡下,除了在编辑器中通过红色下划线提示外,它们还会在您编辑代码时显示。当您运行该程序时,任何异常都将连同程序输出一起写入控制台。

原文由 Nathan Hughes 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题