Java 即使eclipse没有标记错误,cast在那里是如何工作的

Java 即使eclipse没有标记错误,cast在那里是如何工作的,java,multithreading,concurrency,casting,threadpool,Java,Multithreading,Concurrency,Casting,Threadpool,ThreadPoolExecutor ThreadPoolExecutor=(ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads) 当我查看api文档时,fixedThreadPool()返回executor服务的一个实例,但这里我们正在强制转换fixedThreadPool()对于ThreadPoolExecutor来说,这很奇怪,因为ThreadPoolExecutor实现了executor服务。有人能解释一下这个强制转换是

ThreadPoolExecutor ThreadPoolExecutor=(ThreadPoolExecutor)
Executors.newFixedThreadPool(numThreads)


当我查看api文档时,fixedThreadPool()返回executor服务的一个实例,但这里我们正在强制转换fixedThreadPool()对于ThreadPoolExecutor来说,这很奇怪,因为ThreadPoolExecutor实现了executor服务。有人能解释一下这个强制转换是如何工作的吗?

ADPoolExecutor是ExecutorService接口的一个子类。

正如您所提到的,fixedThreadPool()返回ExecutorService接口的实例。返回的运行时对象实例是ADPool Executor。因此,您的类转换工作正常。

只需运行以下代码:

ExecutorService te = Executors.newFixedThreadPool(10);
System.out.println(te.getClass());
输出:

class java.util.concurrent.ThreadPoolExecutor
正如您所看到的,返回的实例是。这里的
ExecutorService
是一个接口,
ThreadPoolExecutor
实现它。
您可以从超级类型转换为子类型。因此,它正在发挥作用