Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查InterruptedException的良好实践是什么?_Java - Fatal编程技术网

Java 检查InterruptedException的良好实践是什么?

Java 检查InterruptedException的良好实践是什么?,java,Java,我是Java世界的新手,所以如果这是一个愚蠢的问题,请容忍我 我最近在可运行对象的run()方法中看到了一些类似的代码 try { if (Thread.interrupted()) { throw new InterruptedException(); } // do something if (Thread.interrupted()) { throw new InterruptedException(); }

我是Java世界的新手,所以如果这是一个愚蠢的问题,请容忍我

我最近在可运行对象的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
}

检查线程中断的频率和位置,什么是好的做法?

通常您不会在代码中随意使用。但是,如果您希望能够取消异步任务,则可能需要定期检查中断。换句话说,这通常是在确定需要对中断做出更大响应的代码体之后添加的。我通常看不到正在使用的线程中断机制-同样,如果代码没有中断线程,那么线程不需要检查它们是否被中断。然而,如果您的程序正在使用线程中断机制,那么将If(thread.interrupted())检查放在Runnable中的顶级循环中是一个很好的位置:Runnable通常看起来像

run() {
    while(true) {
        ...
    }
}
run() {
    try {
        while(true) {
            if(Thread.interrupted()) {
                throw new InterruptedException();
            }
            ...
         }
    } catch (InterruptedException ex) {
        ...
    }
}
而你的看起来像

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

线程只有在有人调用其方法时才会中断。如果您从未调用
interrupt()
,并且您没有使用调用
interrupt()
的库(这是您所期望的内容),那么您就不需要检查中断


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

谢谢,对于包含无限循环的run()方法,我认为这可能是标准模式。谢谢,用户是否可以按键或鼠标点击中断计数?我只想到另一种情况:我们可以将它放在长时间执行之前,因此如果中断发生在线程进入该部分之前,我们可以终止线程,而不会浪费cpu或内存去做一些不再有效的事情。@jAckOdE-中断是一些代码调用
thread.interrupt()
时发生的事情。