【问题标题】:Why doesn't Catch Print?为什么不捕捉打印?
【发布时间】:2013-06-07 11:20:13
【问题描述】:
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted, NOT PRINTED");
}
System.out.println ("This statement is printed");

在这段代码中,sleep 抛出了一个中断的异常,但这并没有在输出中打印 catch 语句。为什么?

【问题讨论】:

  • 中断在哪里完成?我看这里没有扔东西。
  • 在开头添加Thread.currentThread().interrupt()
  • sleep 方法应该抛出异常,它的原型有点像这样:static void sleep(long milliseconds) throws InterruptedException
  • @Mayank - 睡眠方法可能抛出异常,if睡眠线程被中断。它不保证这样做。

标签: java exception try-catch thread-sleep


【解决方案1】:

您应该阅读完整的 Javadoc 以了解 sleep 方法(注意重点):

睡觉

public static void sleep(long millis) throws InterruptedException

使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性。线程不会失去任何监视器的所有权。

参数
millis - 以毫秒为单位的睡眠时间长度。
抛出
InterruptedException - 如果任何线程中断了当前线程。抛出该异常时清除当前线程的中断状态。

不会抛出异常除非睡眠线程实际上被中断了。以下是更可靠地测试您正在检查的行为的代码版本:

Thread targetThread = new Thread() {
    @Override
    public void run() {
        try {
            Thread.sleep(5000);
            System.out.println("Target thread completed normally");
        } catch(final InterruptedException ie) {
            System.out.println("Target thread was interrupted");
        }
    }
};

targetThread.start();
targetThread.interrupt();

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多