【问题标题】:Does InterruptedIOException set the Interrupted flag of the thread to true?InterruptedIOException 是否将线程的 Interrupted 标志设置为 true?
【发布时间】:2019-02-14 11:37:58
【问题描述】:

我的代码中有一个中断异常,我正在尝试了解原因。

发生的情况是我试图通过调用 FilesUtils.filesMethod() 在我的文件系统中的某个位置创建文件。

如果我收到 IOException,我会尝试休眠 100 毫秒。 在睡眠期间我需要检查我是否被打断(因为 InterruptedException 是睡眠检查异常)。

如果是这样,我打印“Got interrupted”并将当前线程的中断标志设置为 true。

我的日志中显示“被打断了”。

在我的代码中没有任何地方对该线程的命令 interrput()。

会是什么?

这个场景是否有意义:

  1. ilesUtils.filesMethod() 方法抛出 InterruptedIOException,因为流在​​线程脚下关闭。此外,此 InterruptedIOException 将 Interrupted 标志设置为 true。

  2. 我在我的 catch (IOException e) 中捕获了 InterruptedIOException。

  3. 睡眠检查中断标志是否为真。它是(见 1)所以它抛出 InterruptedException。

会是这样吗?

        try {
            FilesUtils.filesMethod();
            break;
        } catch (IOException e) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e1) {
                log.info("Got interrupted", e1);
                Thread.currentThread().interrupt();
            }
        }

【问题讨论】:

    标签: java multithreading interrupt interrupt-handling


    【解决方案1】:

    在不知道YourFilesUtils.filesMethod()的实现细节的情况下,我们只能猜测这里发生了什么。 但只是抛出InterruptedIOException 不会导致设置中断标志。

    我猜FilesUtils.filesMethod() 在抛出InterruptedIOException 之前设置了interrupt 标志,然后sleep 方法抛出InterruptedException(因为设置了中断标志)。

    您可以在调用 sleep 方法之前使用Thread.interrupted() 清除中断标志(如果您希望在这种情况下能够休眠)。所以 sleep 方法不会抛出InterruptedException。(如果线程没有再次被中断)

    【讨论】:

    • 谢谢。刚刚看到 sleep() 方法在调试期间抛出了 InterruptedException。我试图在调试模式下通过 Thread.interrupted() 清除标志,然后再次运行睡眠 - 但是(!)这是有趣的部分 - 它不起作用。即使在 Thread.interrupted() 之后,睡眠仍然会抛出 InterruptedException。我什至在调试模式下检查标志 - 它是错误的。知道为什么睡眠会抛出这个 InterruptedException 吗?谢谢!
    • @YotamEliraz 我可以想到两种情况,首先如果从 ExecutorService 调用此方法,则为 ExecutorService 调用 shutdownNow() 会导致其池线程的中断标志被设置。第二个 interrupt() 调用了这个线程。(但你说没有这样的调用)。
    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 2014-10-19
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    相关资源
    最近更新 更多