当一个程序有多个 ThreadPoolExecutor 时会发生什么?

What happens when a single program has multiple `ThreadPoolExecutor`s?

一个ThreadPoolExecutor实例管理线程:它负责将队列中的任务匹配到一定数量的线程。

鉴于线程是公共资源,直觉上它们应该由每个应用程序 "one manager" 管理。

但是,存在 "best practices" 告诉您为某些场景创建多个执行程序。例如,有人认为您应该创建两个独立的执行器,一个用于 CPU 绑定任务,另一个用于阻塞 IO 任务。

为什么会这样?

直觉上,让多个 "managers" 管理同一组线程,而不知道彼此的存在对我来说听起来像是一种反模式。

JVM 是否知道多个执行程序的存在并执行额外的管理以确保它们永远不会争用同一个线程?

我真的建议你看看"Java concurrency in Practice"这本书。

仅引用第 8 章中的一些内容:

Thread pools work best when tasks are homogeneous and independent. Mixing long-running and short-running tasks risks "clogging" the pool unless it is very large; submitting tasks that depend on other tasks risks deadlocks unless the pool is unbounded.

...

Thread pools can have responsiveness problems if tasks can block for extended periods of time, even if deadlock is not a possibility. A thread pool can become clogged with long-running tasks, increasing the service time even for short tasks. If the pool size is too small relative to the expected steady-state number of longrunning tasks, eventually all the pool threads will be running long-running tasks and responsiveness will suffer.

通过将长 运行 IO 任务和快速 CPU 任务分成两个不同的线程池,您可以缓解此问题。线程池不会争夺同一个线程,因为它们不共享任何线程。