当我调用 Future.cancel()
时,如何确保我的任务响应中断?
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> future = executor.submit(task);
try {
future.get(timeout, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true);
}
最佳答案
How to ensure that my tasks are responsive to interruption when I call Future.cancel()?
调用 future.cancel(...)
将停止尚未运行的任务。如果它正在运行,那么如果您使用 future.cancel(true)
它将中断正在运行的线程。
要停止线程,您需要测试线程中断标志:
if (!Thread.currentThread().isInterrupted()) {
...
并且您需要适本地处理 handle InterruptedException
。例如:
try {
Thread.sleep(...);
} catch (InterruptedException e) {
// re-establish the interrupt condition
Thread.currentThread.interrupt();
// probably stop the thread
return;
}
请参阅我关于 threads not interrupting 的回答.
关于java - 确保任务是可中断的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18702482/