检查InterruptedException的好方法是什么?

jAc*_*OdE 4 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
}
Run Code Online (Sandbox Code Playgroud)

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

jta*_*orn 5

它通常不是你在代码中撒了一些东西.但是,如果您希望能够取消异步任务,则可能需要定期检查中断.换句话说,这是典型的东西,你想补充,当你识别代码的一个机构,其需要更加适应中断的事实.