问题描述
newCachedThreadPool()
与 newFixedThreadPool()
我什么时候应该使用其中一种?哪种策略在资源利用方面更好?
When should I use one or the other? Which strategy is better in terms of resource utilization?
推荐答案
我认为文档很好地解释了这两个函数的区别和用法:
I think the docs explain the difference and usage of these two functions pretty well:
创建一个重用一个线程池固定数量的线程关闭一个共享的无界队列.在任何点,最多 nThreads 个线程将是主动处理任务.如果额外的任务在什么时候提交所有线程都处于活动状态,它们将等待在队列中,直到一个线程可用的.如果任何线程终止由于执行过程中失败在关闭之前,一个新的将需要如果需要执行它的位置后续任务.中的线程池将一直存在,直到它被明确关掉.
创建一个线程池来创建新的线程根据需要,但会重用先前构造的线程,当他们是可用的.这些池将通常会提高性能执行许多短命的程序异步任务.调用执行将重用之前构建的线程(如果可用).如果不存在线程可用,新线程将被创建并添加到池中.未使用的线程六十秒终止并且从缓存中删除.因此,一个池保持空闲足够长的时间将不消耗任何资源.注意池具有相似的属性,但不同的细节(例如,超时参数)可以创建使用 ThreadPoolExecutor 构造函数.
在资源方面,newFixedThreadPool
将保持所有线程运行,直到它们被明确终止.在 newCachedThreadPool
中,60 秒内未使用的线程将被终止并从缓存中删除.
In terms of resources, the newFixedThreadPool
will keep all the threads running until they are explicitly terminated. In the newCachedThreadPool
Threads that have not been used for sixty seconds are terminated and removed from the cache.
鉴于此,资源消耗将在很大程度上取决于情况.例如,如果您有大量长时间运行的任务,我建议使用 FixedThreadPool
.至于 CachedThreadPool
,文档说这些池通常会提高执行许多短期异步任务的程序的性能".
Given this, the resource consumption will depend very much in the situation. For instance, If you have a huge number of long running tasks I would suggest the FixedThreadPool
. As for the CachedThreadPool
, the docs say that "These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks".
这篇关于Executors.newCachedThreadPool() 与 Executors.newFixedThreadPool()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!