InterruptedException异常的原因(The Cause of Interrupted

2019-07-23 05:54发布

包括J2ME DOC我们知道:

当一个线程在等待停顿了很长一段时间另一个线程中断,java.lang.InterruptedException抛出,睡觉,或以其他方式和。

现在的问题是,如果它的更多钞票来获得这样的异常,如果从一个线程我叫Thread.Interupt()其他线程运行,其中()其他线程等待InputStream.Read的方法(Char [] buf)指向?

Answer 1:

的行为阻读取响应中断是线程,其实就是不确定的。 见这个长期存在的错误的详细信息。 它的短是,有时你会得到EOF,有时你IOException异常。



Answer 2:

不幸的是,不, java.io.*类不来打扰他们被阻挡在读取或写入方法时作出回应。 通常,你所要做的就是关闭流,然后处理IOException获取引发。 我有这样的模式在我的代码重复:

try {
    for (;;) {
        try {
            inputStream.read(data);

            thread.join();
        }
        catch (IOException exception) {
            // If interrupted this isn't a real I/O error.
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
            else {
                throw exception;
            }
        }
    }
}
catch (InterruptedException exception) {
}

或者较新java.nio.*类做处理中断更好,产生InterruptedIOException时候,他们被中断。 请注意,此异常源自IOException ,而不是从InterruptedException ,所以你可能会需要两个catch条款来处理任何类型的例外,一个InterruptedException ,一个用于InterruptedIOException 。 你会想要的任何内部IOException catch子句忽略InterruptedIOException秒。



文章来源: The Cause of InterruptedException
标签: java java-me