问题描述
我对于为什么以下强制转换不起作用感到非常困惑:
I am extremely confused as to why the following cast does not work:
ScheduledThreadPoolExecutor timeoutControl = (ScheduledThreadPoolExecutor) Executors.newSingleThreadScheduledExecutor();
ScheduledThreadPoolExecutor实现ScheduledExecutorService.如果我不能在实际的课程中使用此执行器,那有什么意义呢?
ScheduledThreadPoolExecutor implements the ScheduledExecutorService. What's the point of this Executors call if I can't use it with an actual class.
我使用错了吗(可能是),有人可以提供一些指导吗?
Am I using it wrong (probably), could someone offer some guidance please?
推荐答案
问题是Executors.newSingleThreadScheduledExecutor();
实际上不返回ScheduledThreadPoolExecutor
.
:
Source code in the Executors
class:
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
Delegated...
类(也有一个DelegatedExecutorService
)只是将所有调用传递给基础执行程序,在本例中为ScheduledThreadPoolExecutor
.代码中的注释表明,这些类的全部要点是隐藏基础执行程序可能具有的所有非接口方法.
The Delegated...
classes (there's a DelegatedExecutorService
too) are just passing all the calls to the underlying executor, the ScheduledThreadPoolExecutor
in this case. The comments in the code suggest that the whole point of these classes is to hide all the non-interface methods that the underlying executor might have.
无论如何,最好还是使用接口而不是要处理的对象的类版本(List
而不是ArrayList
,ScheduledExecutorService
而不是ScheduledThreadPoolExecutor
).
In any case, it is better practice anyway to use the interface rather than the class version of the object you are working on (List
and not ArrayList
, ScheduledExecutorService
and not ScheduledThreadPoolExecutor
).
如果您绝对需要ScheduledThreadPoolExecutor
中可用的功能,而不是ScheduledExecutorService
中可用的功能,则可以使用ScheduledThreadPoolExecutor
的构造函数来创建它的实例.
If you absolutely need functionality available in ScheduledThreadPoolExecutor
and not in the ScheduledExecutorService
, you could use the constructor of ScheduledThreadPoolExecutor
to create an instance of it.
这篇关于使用执行程序创建ScheduledThreadPoolExecutor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!