【问题标题】:How is the cast working there even the eclipse is not flagging an error即使日食没有标记错误,演员如何在那里工作
【发布时间】:2021-07-05 23:03:30
【问题描述】:

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

当我查看 api 文档时,fixedThreadPool() 返回了一个执行器服务实例,但在这里我们将 fixedThreadPool() 转换为 ThreadPoolExecutor,这很奇怪,因为 ThreadPoolExecutor 实现了执行器服务,谁能解释一下这个转换是如何工作的? ?

【问题讨论】:

    标签: java multithreading concurrency casting threadpool


    【解决方案1】:

    TheadPoolExecutor 是 ExecutorService 接口的子类。 https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html

    正如你提到的,fixedThreadPool() 返回一个 ExecutorService 接口的实例。返回的运行时对象实例是 TheadPoolExecutor。所以你的班级演员正在工作。

    【讨论】:

      【解决方案2】:

      只需运行以下代码:

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

      输出:

      class java.util.concurrent.ThreadPoolExecutor
      

      如您所见,返回的实例是ThreadPoolExecutor。这里ExecutorService 是一个接口,ThreadPoolExecutor 实现了它。
      您可以从超类型转换为子类型。所以它正在工作。

      【讨论】:

        猜你喜欢
        • 2023-04-06
        • 1970-01-01
        • 2021-05-06
        • 2015-02-15
        • 1970-01-01
        • 2021-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多