首页 > 解决方案 > 无法将 Executors.newSingleThreadExecutor() 的结果转换为 ThreadPoolExecutor

问题描述

ThreadPoolExecutor文档(here)上,它说使用 Executors 类来创建公共线程,我只想有一个线程,所以我使用Executors.newSingleThreadExecutor它并将其转换ThreadPoolExecutor为我看到的其他示例所做的那样,但这会抛出一个java.lang.ClassCastException. 这是我复制它的最小化代码。

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Test {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newSingleThreadExecutor();
    }
}

标签: javathreadpoolexecutor

解决方案


一般来说,在做出这样的期望之前,我总是会寻找某种合同定义。文档没有明确说明Executors.newSingleThreadExecutor()将返回ThreadPoolExecutor类型对象。此外,这种实施(没有合同)将来可能会改变。

在这种情况下,newSingleThreadExecutor()返回 a ExecutorServicewhich 下面是 aThreadPoolExecutor但包裹在 a 中 FinalizableDelegatedExecutorService。这个类或多或少是它的兄弟ThreadPoolExecutor,因此不能强制转换为它。我想这样做是为了:

保证返回的执行程序不可重新配置以使用额外的线程

根据您想要实现的目标,您应该考虑:
- 使用ExecutorServicereturn fromnewSingleThreadExecutor()而不是ThreadPoolExecutor;
-newFixedThreadPool(1)用来获取ThreadPoolExecutor.


推荐阅读