我是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
}

多久一次,应该在哪里检查线程中断,这是一个好的做法?

最佳答案

通常,您不会在整个代码中散布这些内容。但是,如果希望能够取消异步任务,则可能需要定期检查中断。换句话说,当您确定需要对中断有更好响应的代码体之后,通常会在此之后添加一些内容。

07-25 23:49
查看更多