gpt4 book ai didi

java - 它是否正确? ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads);

转载 作者:行者123 更新时间:2023-11-29 07:55:45 34 4
gpt4 key购买 nike

这是正确的吗?

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

我正在这样做,因为如果我进行类型转换,我将可以访问 getActiveCount()getQueue() 方法。 Eclipse 未在此处标记任何错误,但我想确保我所做的是正确的。

这很奇怪,实际上,因为 ThreadPoolExecutor 实现了 ExecutorService 而我正在将 ExecutorService 转换为 ThreadPoolExecutor

最佳答案

虽然我通常会同意@Evgeniy 所说的原因,但在这种特定情况下实际上没问题,因为 ThreadPoolExecutor 的 Javadoc 特别建议使用工厂方法来创建实例。

我认为这是一项契约(Contract)义务,即这些方法将返回预期的 ThreadPoolExecutor。我不会依赖于查看源代码,因为它会随着时间而改变,但 javadoc 中的明确建议应该是可靠的。

来自 ThreadPoolExecutor 的 javadoc

To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers are urged to use the more convenient Executors factory methods Executors.newCachedThreadPool() (unbounded thread pool, with automatic thread reclamation), Executors.newFixedThreadPool(int) (fixed size thread pool) and Executors.newSingleThreadExecutor() (single background thread), that preconfigure settings for the most common usage scenarios. Otherwise, use the following guide when manually configuring and tuning this class:

关于java - 它是否正确? ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17881394/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com