问题描述
我可能会想象一些任务计划花费很长时间并且 ScheduledThreadPoolExecutor
会为需要运行的其他任务创建额外的线程,直到最大线程数已经到了。
I may imagine some tasks scheduled to take a very long time and ScheduledThreadPoolExecutor
would create additional threads for the other tasks that need to be run, until a maximum number of threads is reached.
但似乎我只能为池指定固定数量的线程,为什么会这样呢?
But seems that I can only specify a fixed number of threads for the pool, why is that so ?
推荐答案
作为原因,我也不知道。但我可以想象。
As the why, I don't know either. But I can imagine.
计算机的资源量有限。并非所有资源都可以同时处理。
The amount of resources of a computer is limited. Not all resources can be handled concurrently either.
如果多个进程同时加载文件,它们的加载速度将比顺序加载(至少在硬盘上) 。
If multiple processes concurrently load files, they will be loaded slower than if they were being loaded sequentially (at least on a harddisk).
处理器对同时处理多个线程的支持也有限。在某些时候,OS或JVM将花费更多的时间来切换线程,而不是线程花费在执行代码上。
A processor also has limited support for handling multiple threads concurrently. At some point the OS or JVM will spend more time switching threads, than threads spend executing their code.
这是 ScheduledThreadPoolExecutor的一个很好的理由
按照原样设计。您可以在队列中放置任意数量的作业,但从不会同时执行比可以有效运行的更多作业。当然,这取决于你的平衡。
That is a good reason for the ScheduledThreadPoolExecutor
to be designed the way it is. You can put any amount of jobs on the queue, but there are never executed more jobs at the same time than can be run efficiently. It's up to you to balance that, of course.
如果你的任务是IO绑定的,我会将池大小设置得很小,如果它们是CPU绑定的,有点大(32左右)。您还可以创建多个 ScheduledThreadPoolExecutor
,一个用于IO绑定任务,另一个用于CPU绑定任务。
If your tasks are IO bound, I'd set the pool size small, and if they are CPU bound, a bit larger (32 or so). You can also make multiple ScheduledThreadPoolExecutor
s, one for IO bound tasks and one for CPU bound tasks.
这篇关于为什么ScheduledThreadPoolExecutor只接受固定数量的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!