← 中文资源

简体中文版本

shutdownNow 抽走未启动的排队任务

shutdownNow 中断正在执行的任务并抽走队列:返回值就是从未 commence 的任务列表,对应的 future 直接进入已取消状态,比单纯 close 更能看清丢弃了什么。

阅读英文原文

实现说明

shutdownNow 抽走未启动的排队任务以类 GracefulAbandon为骨架。

使用要点

  • 每一步打印都带着自己的标签:drained queued:、running result:、queued futures done:。

常见问题

运行「shutdownNow 抽走未启动的排队任务」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 drained queued:、running result:、queued futures done: 这类标签。

核心语句

ExecutorService pool = Executors.newSingleThreadExecutor();
return "interrupted";
return "finished";

代码示例

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class GracefulAbandon {

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        CountDownLatch started = new CountDownLatch(1);
        CountDownLatch release = new CountDownLatch(1);

        Future<String> running = pool.submit(() -> {
            started.countDown();
            try {
                release.await(); // 阻塞点:shutdownNow 的中断会让它抛异常
            } catch (InterruptedException e) {
                return "interrupted";
            }
            return "finished";
        });
        Future<String> queuedA = pool.submit(() -> "queued-a");
        Future<String> queuedB = pool.submit(() -> "queued-b");

        started.await(); // 第一个 task 已在运行,另外两个仍 queued 在队列里
        List<Runnable> neverStarted = pool.shutdownNow(); // 抽走 queued tasks
        System.out.println("drained queued: " + neverStarted.size());
        release.countDown();

        System.out.println("running result: " + running.get());
        // 被撤下的排队任务对应的 future 直接标记为已取消
        System.out.println("queued futures done: " + queuedA.isDone() + " / " + queuedB.isDone());
    }
}