确保任务可中断 [英] Ensure that a task is interruptible

查看:76
本文介绍了确保任务可中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我致电Future.cancel()时如何确保我的任务对中断有反应?

How to ensure that my tasks are responsive to interruption when I call Future.cancel()?

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> future = executor.submit(task);

try {
    future.get(timeout, timeoutUnit);
} catch (TimeoutException e) {
    future.cancel(true);
}

推荐答案

当我调用Future.cancel()时如何确保我的任务能够响应中断?

How to ensure that my tasks are responsive to interruption when I call Future.cancel()?

调用future.cancel(...)将停止尚未运行的任务.如果它正在运行,则使用future.cancel(true)它将中断正在运行的线程.

Calling future.cancel(...) will stop the task it has not been run yet. If it is being run then if you use future.cancel(true) it will interrupt the running thread.

要停止线程,您需要测试线程中断标志:

To stop the thread you need to test the thread interrupt flag:

if (!Thread.currentThread().isInterrupted()) {
   ...

并且您需要适当地处理InterruptedException句柄.例如:

And you need to handle handle InterruptedException appropriately. For example:

try {
    Thread.sleep(...);
} catch (InterruptedException e) {
    // re-establish the interrupt condition
    Thread.currentThread.interrupt();
    // probably stop the thread
    return;
}

请参阅有关线程不中断的答案.

这篇关于确保任务可中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆