繁体   English   中英

InterruptedException的原因

[英]The Cause of InterruptedException

从J2me doc我们知道:

java.lang.InterruptedException当线程等待,休眠或以其他方式暂停很长一段时间并且另一个线程中断它时抛出。

问题是,如果从一个线程调用Thread.Interupt()为其他线程,其他线程的Run()方法在InputStream.Read(char [] buf)上等待,是否可以获得此类异常?

事实上,阻止读取响应线程中断的行为是未定义的。 有关详细信息,请参阅此长期错误 缺点是有时你会得到EOF,有时你会得到IOException。

不幸的是,不, 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时生成InterruptedIOException 请注意,此异常是从IOException派生而不是从InterruptedException派生的,因此您可能需要两个catch子句来处理任一类型的异常,一个用于InterruptedException ,另一个用于InterruptedIOException 并且您将需要任何内部IOException catch子句来忽略InterruptedIOException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM