且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何决定使用newCachedThreadPool还是newFixedThreadPool?

更新时间:2023-11-10 21:02:28

所以现在我想知道的是-我应该在代码中使用newFixedThreadPool还是newCachedThreadPool吗?

So now I am wondering is - Should I use newFixedThreadPool or newCachedThreadPool in my code?

要引用Javadocs,请引用newFixedThreadPool():

To quote from the Javadocs, the newFixedThreadPool():

创建一个重用固定数量线程的线程池...

Creates a thread pool that reuses a fixed number of threads...

这意味着,如果您请求2个线程,它将启动2个线程,而从不启动3个线程.另一方面,newCachedThreadPool():

This means that if you ask for 2 threads, it will start 2 threads and never start 3. On the other hand, the newCachedThreadPool():

创建一个线程池,该线程池可根据需要创建新线程,但在可用时将重用以前构造的线程.

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.

在您的情况下,如果您只有2个线程要运行,则任何一个都可以正常工作,因为您只会向池中提交2个作业.但是,如果要一次提交所有20个作业,但一次只运行2个作业,则应使用newFixedThreadPool(2).如果使用缓存池,则20个作业中的每个作业都会启动一个线程,该线程将同时运行,这可能不是***选择,具体取决于您拥有的CPU数.

In your case, if you only have 2 thread to run, either will work fine since you will only be submitting 2 jobs to your pool. However, if you wanted to submit all 20 jobs at once but only have 2 jobs running at one time, you should use a newFixedThreadPool(2). If you used a cached pool then each of the 20 jobs will start a thread which will run at the same time which may not be optimal depending on how many CPUs you have.

通常,当我需要要立即产生的线程时,即使当前正在运行的所有线程都在忙,我也会使用newCachedThreadPool().我最近在生成计时器任务时使用了它.并发作业的数量无关紧要,因为我从来没有产生太多,但是我希望它们在被请求时运行,并且希望它们重新使用休眠线程.

Typically I use the newCachedThreadPool() when I need the thread to be spawned immediately, even if all of the threads currently running are busy. I recently used it when I was spawning timer tasks. The number of concurrent jobs are immaterial because I never spawn very many but I want them to run when they are requested and I want them to re-use dormant threads.

当我想限制在任一点运行的并发任务的数量以最大化性能而不淹没服务器时,我使用了newFixedThreadPool().例如,如果我要处理一个文件中的10万行,一次只能处理一行,我不希望每一行都启动一个新线程,但是我想要某种程度的并发性,因此我分配了(例如)10个固定线程来运行直到池耗尽为止.

I used newFixedThreadPool() when I want to limit the number of concurrent tasks running at any one point to maximize performance and not swamp my server. For example if I am processing 100k lines from a file, one line at a time, I don't want each line to start a new thread but I want some level of concurrency so I allocate (for example) 10 fixed threads to run the tasks until the pool is exhausted.