← 中文资源

简体中文版本

Future.cancel 中断运行中的任务

cancel(true) 会向正在执行 Future 的工作线程发出中断并标记任务已取消,此后调用 get() 只会抛 CancellationException,永远拿不到返回值。

阅读英文原文

实现说明

底层就是类 ReportJob。 循环只出现在 for (int round = 1; round <= 100; round++),它的每次迭代处理一个元素。

使用要点

  • 每一步打印都带着自己的标签:cancel(true) accepted:、isCancelled:。

常见问题

运行「Future.cancel 中断运行中的任务」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 cancel(true) accepted:、isCancelled: 这类标签。

核心语句

ExecutorService pool = Executors.newSingleThreadExecutor();
Thread.currentThread().interrupt(); // restore the interrupt flag before exiting
return "interrupted";
Thread.sleep(50); // each pass takes time, the whole job is far from done
}

代码示例

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ReportJob {

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> job = pool.submit(() -> {
            try {
                for (int round = 1; round <= 100; round++) {
                    Thread.sleep(50); // each pass takes time, the whole job is far from done
                }
                return "done";
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // restore the interrupt flag before exiting
                return "interrupted";
            }
        });

        Thread.sleep(120); // let it run roughly two passes first
        System.out.println("cancel(true) accepted: " + job.cancel(true));
        System.out.println("isCancelled: " + job.isCancelled() + ", isDone: " + job.isDone());
        try {
            job.get(); // a cancelled task never produces a result
        } catch (CancellationException e) {
            System.out.println("get() on cancelled future -> CancellationException");
        }
        pool.shutdownNow();
    }
}