java - 当单个程序有多个 `ThreadPoolExecutor` 时会发生什么?

标签 java multithreading threadpool executorservice threadpoolexecutor

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

鉴于线程是公共(public)资源,直观上​​它们应该由每个应用程序的“一个管理器”进行管理。

但是,存在“最佳实践”,告诉您为某些场景创建多个执行程序。例如,有人认为您应该创建两个单独的执行器,一个用于 CPU 密集型任务,另一个用于阻塞 IO 任务。

为什么会这样?

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

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

最佳答案

我强烈推荐你看看《Java并发实践》一书。

仅引用第 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 任务拆分到两个不同的线程池中,您可以缓解此问题。线程池不会争夺同一个线程,因为它们不共享任何线程。

关于java - 当单个程序有多个 `ThreadPoolExecutor` 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60465783/

相关文章:

java - 何时使用 JFrame 或 JPanel

java - 2D Peak finding algorithm JAVA,找到了一个例子,但不会编码

java - 对 Swing 的撤消管理器隐藏某些操作

C#线程不会休眠?

java - 指定 ThreadPoolExecutor 问题

java - Java固定线程池有最大尺寸参数吗?

java - 有意停止服务

java - 如何在 Java 中调试 Thread.start()

Java并发问题——在一个集合上同步

java - 在 Threads 中访问作用域代理 bean