InterruptedIOException是否将线程的Interrupted标志设置为true?

问题描述 投票:1回答:1

我的代码中有一个中断的异常,我试图理解为什么。

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

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

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

我正在将“已中断”打印到我的日志中。

在我的代码中没有任何地方有这个线程的命令interrupt()。

会是什么呢?

这种情况是否有意义:

  1. ilesUtils.filesMethod()的方法抛出InterruptedIOException,因为流已在线程feets下关闭。此InterruptedIOException也将Interrupted标志设置为true。
  2. 我在catch(IOException e)中捕获了InterruptedIOException。
  3. 睡眠检查Interrupted标志是否为真。它是(见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个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.