java - 无法将 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();
}
}
解决方案
一般来说,在做出这样的期望之前,我总是会寻找某种合同定义。文档没有明确说明Executors.newSingleThreadExecutor()
将返回ThreadPoolExecutor
类型对象。此外,这种实施(没有合同)将来可能会改变。
在这种情况下,newSingleThreadExecutor()
返回 a ExecutorService
which 下面是 aThreadPoolExecutor
但包裹在 a 中
FinalizableDelegatedExecutorService
。这个类或多或少是它的兄弟ThreadPoolExecutor
,因此不能强制转换为它。我想这样做是为了:
保证返回的执行程序不可重新配置以使用额外的线程
根据您想要实现的目标,您应该考虑:
- 使用ExecutorService
return fromnewSingleThreadExecutor()
而不是ThreadPoolExecutor
;
-newFixedThreadPool(1)
用来获取ThreadPoolExecutor
.
推荐阅读
- c++ - 给定值之前触发的函数
- postgresql - 在 knex 查询中使用 postgres 函数“arr agg”时出错
- java - 有没有办法在一个安卓设备上同时使用两个外部音量键来获得第三个独特的输出?
- c++ - 如何为非字符串的自定义选项值类型处理 Boost::program_options 配置文件中的空格?
- javascript - React 没有重新渲染
- javascript - 数据表不想从 API 中提取数据
- arduino-uno - 使用数组时arduino冻结
- c# - 如何设置redirect_uri登录google .Net Core 2,Docker
- f# - 对象同步异常仅在使用断点时,在 F#
- javascript - 使用 Regex 和 Jquery 替换页面内多