当我调用Future.cancel()时,如何确保我的任务能够响应中断?
调用
future.cancel(...)将停止尚未运行的任务。如果它正在运行,那么如果使用
future.cancel(true)它将中断正在运行的线程。
要停止线程,您需要测试线程中断标志:
if (!Thread.currentThread().isInterrupted()) { ...并且您需要
InterruptedException适当处理句柄。例如:
try { Thread.sleep(...);} catch (InterruptedException e) { // re-establish the interrupt condition Thread.currentThread.interrupt(); // probably stop the thread return;}


