保证 ExecutorService 实例的线程种类

Guarantees for kind of threads for ExecutorService instances

各种ExecutorService instances created by Executors and ForkJoinPool.commonPool()当然有完全不同的行为。

如果您尝试下面的示例程序(及其变体),您应该会看到它只打印 "false"。由于使用 daemon threads 的服务会在主线程死亡时死亡,这当然是可以预料的。但我无法在除源代码之外的任何地方找到这种行为的记录,所以我如何确定这在未来不会改变?

如果我不能确定在创建这样的 ExecutorService 实例时是否会使用守护线程,我应该如何以保证我想要的行为的方式创建它们?

import java.util.concurrent.*;

class ExecutorsTest {
    public static void main(String[] args) {
        // These use normal threads
        // ExecutorService es = Executors.newSingleThreadExecutor();
        // ExecutorService es = Executors.newCachedThreadPool();

        // These use daemon threads
        ExecutorService es = Executors.newWorkStealingPool();
        // ExecutorService es = ForkJoinPool.commonPool();

        es.execute(() -> {
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().isDaemon());
        });
    }
}

您不应依赖特定 JRE/JDK 实现的未记录的功能。

如果你想确保线程是守护进程或者有特定的线程名称,你可以使用 ThreadFactory API 来构造它们:

Executors.newFixedThreadPool(int nThreads, ThreadFactory threadFactory)

由于某种原因,Executors API 中没有对应的方法 WorkStealingPool 接受 ThreadFactory.