简体   繁体   English

InterruptedException的原因

[英]The Cause of InterruptedException

From J2me doc we know that: 从J2me doc我们知道:

java.lang.InterruptedException Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it. java.lang.InterruptedException当线程等待,休眠或以其他方式暂停很长一段时间并且另一个线程中断它时抛出。

The question is if it's posible to get such exception if from one thread i call Thread.Interupt() for other thread where Run() method of other thread waiting on InputStream.Read(char[]buf) ? 问题是,如果从一个线程调用Thread.Interupt()为其他线程,其他线程的Run()方法在InputStream.Read(char [] buf)上等待,是否可以获得此类异常?

The behavior of blocking read in response to thread interrupt is, in fact, undefined. 事实上,阻止读取响应线程中断的行为是未定义的。 See this long-standing bug for details. 有关详细信息,请参阅此长期错误 The short of it is that sometimes you get EOF, sometimes you get IOException. 缺点是有时你会得到EOF,有时你会得到IOException。

Unfortunately, no, the java.io.* classes do not respond to interruptions when they are blocked in read or write methods. 不幸的是,不, java.io.*类在读取或写入方法中被阻止时不会响应中断。 Typically what you have to do is close the stream and then handle the IOException that gets thrown. 通常,您需要关闭流,然后处理抛出的IOException I have this pattern repeated throughout my code: 我在整个代码中重复了这种模式:

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) {
}

Alternatively the newer java.nio.* classes do handle interruptions better and generate InterruptedIOException s when they are interrupted. 或者,较新的java.nio.*类可以更好地处理中断,并在InterruptedIOException时生成InterruptedIOException Note that this exception is derived from IOException and not from InterruptedException so you will probably need two catch clauses to handle either type of exception, one for InterruptedException and one for InterruptedIOException . 请注意,此异常是从IOException派生而不是从InterruptedException派生的,因此您可能需要两个catch子句来处理任一类型的异常,一个用于InterruptedException ,另一个用于InterruptedIOException And you'll want any inner IOException catch clause to ignore InterruptedIOException s. 并且您将需要任何内部IOException catch子句来忽略InterruptedIOException

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

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