关于ZAKER 融媒体解决方案 合作 加入

java – Executors.newCachedThreadPool ( ) 与 Executors

CocoaChina 09-19

最佳答案

我认为文档很好地解释了这两个函数的区别和用法:

newFixedThreadPool

Creates a thread pool that reuses a

fixed number of threads operating off

a shared unbounded queue. At any

point, at most nThreads threads will

be active processing tasks. If

additional tasks are submitted when

all threads are active, they will wait

in the queue until a thread is

available. If any thread terminates

due to a failure during execution

prior to shutdown, a new one will take

its place if needed to execute

subsequent tasks. The threads in the

pool will exist until it is explicitly

shutdown.

newCachedThreadPool

Creates a thread pool that creates new

threads as needed, but will reuse

previously constructed threads when

they are available. These pools will

typically improve the performance of

programs that execute many short-lived

asynchronous tasks. Calls to execute

will reuse previously constructed

threads if available. If no existing

thread is available, a new thread will

be created and added to the pool.

Threads that have not been used for

sixty seconds are terminated and

removed from the cache. Thus, a pool

that remains idle for long enough will

not consume any resources. Note that

pools with similar properties but

different details ( for example,

timeout parameters ) may be created

using ThreadPoolExecutor constructors.

在资源方面 ,newFixedThreadPool 将保持所有线程运行 , 直到它们被明确终止 . 在 newCachedThreadPool 中 , 未使用 60 秒的线程终止并从缓存中删除 .

鉴于此 , 资源消耗将在很大程度上取决于具体情况 . 例如 , 如果您有大量长时间运行的任务 , 我会建议使用 FixedThreadPool. 对于 CachedThreadPool, 文档说 " 这些池通常会提高执行许多短期异步任务的程序的性能 ".

以上内容由"CocoaChina"上传发布 查看原文

觉得文章不错,微信扫描分享好友

扫码分享