检查InterruptedException的好方法是什么?

时间:2013-04-09 02:32:33

标签: java

我是Java世界的新手,如果这是一个愚蠢的问题,请耐心等待。

我最近在Runnable对象的run()方法中看到了类似这样的代码。

try {
    if (Thread.interrupted()) {
       throw new InterruptedException();
    }

    // do something 

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // do something 

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // and so on

} catch (InterruptedException e){
     // Handle exception
} finally {
     // release resource
}

多久一次,在哪里检查线程中断,对它有什么好处?

3 个答案:

答案 0 :(得分:5)

通常情况下,您只是在代码中撒了一些东西。但是,如果您希望能够取消异步任务,则可能需要定期检查中断。换句话说,当您确定需要对中断更敏感的代码体时,通常会在之后添加

答案 1 :(得分:3)

我通常看不到正在使用的线程中断机制 - 同样,如果你的代码没有中断线程,那么线程不需要检查它们是否被中断。但是,如果您的程序使用线程中断机制,那么将if(Thread.interrupted())检查放在Runnable的顶层循环中的好地方:Runnable通常看起来像

run() {
    while(true) {
        ...
    }
}

你的看起来像

run() {
    try {
        while(true) {
            if(Thread.interrupted()) {
                throw new InterruptedException();
            }
            ...
         }
    } catch (InterruptedException ex) {
        ...
    }
}

答案 2 :(得分:2)

只有在有人调用interrupt()方法时才会中断线程。如果您从未致电interrupt(),并且您没有使用调用interrupt()的库(并且这是您希望拼写出的内容),那么您无需检查中断。

某人希望中断线程的主要原因是取消阻塞或长时间运行的任务。例如,锁定机制wait()通常会导致线程永远等待通知,但另一个线程可以中断以强制等待线程停止等待(通常这将取消操作)。