1

这是正确的吗?这是正确的吗? ThreadPoolExecutor threadPoolExecutor =(ThreadPoolExecutor)Executors.newFixedThreadPool(numThreads);

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

我这样做,因为如果我强制转换,我会去getActiveCount()getQueue()方法访问。 Eclipse在这里没有标记任何错误,但我想确保我所做的是正确的。

这很奇怪,实际上,因为ThreadPoolExecutor implements ExecutorService和我铸造ExecutorServiceThreadPoolExecutor

回答

2

尽管我通常会同意@Evgeniy出于他所述的原因,但在此特定情况下实际上可以,因为ThreadPoolExecutor的Javadoc特别推荐使用工厂方法创建实例。

我认为这是合同义务,这些方法将返回预期的ThreadPoolExecutor。我不会依赖于查看源代码,因为这可能随时间而改变,但javadoc中的明确建议应该是可靠的。

从Javadoc中的ThreadPoolExecutor

为了在宽范围的环境是有用的,这类提供许多可调整的参数和扩展的钩。但是,我们敦促程序员使用更方便的Executors工厂方法Executors.newCachedThreadPool()(无界线程池,带自动线程回收),Executors.newFixedThreadPool(int)(固定大小的线程池)和Executors.newSingleThreadExecutor()(单个背景线程),为最常见的使用场景预配置设置。否则,在手动配置和调整此类时,请使用以下指南:

+0

如果他们很乐意遵守这个规则,为什么他们没有在第一时间返回一个'ThreadPoolExecutor'呢?看起来像一个API漏洞。 – bacar

1

您可以查看newFixedThreadPool的源代码并查看它是否返回ThreadPoolExecutor,以便投射不会抛出异常,当然如果将来有人会更改“newFixedThreadPool”的实现,您的代码可能无法正常工作。

public static ExecutorService newFixedThreadPool(int nThreads) { 
     return new ThreadPoolExecutor(nThreads, nThreads, 
             0L, TimeUnit.MILLISECONDS, 
             new LinkedBlockingQueue<Runnable>()); 
    } 
+0

非常感谢您的迅速回复! – ADJ

2

我们知道从Executors.newFixedThreadPool返回的ThreadPoolExecutor但执行人API没有这么说执行人的源代码。因此理论上最好直接用new创建一个ThreadPoolExecutor实例。

+0

谢谢,真正appriciate您的快速回复! – ADJ