java固定线程池和定时线程池的区别

标签 java concurrency threadpool executorservice

我有一个固定的线程池,随时运行 7 个并发线程(带队列),我想将它变成一个调度线程池,它只运行 7 个并发作业,但可以排队/调度更多。

阅读文档并没有真正帮助我..

newFixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads)

Creates a thread pool that reuses a fixed set of threads operating off a shared unbounded queue. 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.

Parameters: nThreads - the number of threads in the pool Returns: the newly created thread pool

newScheduledThreadPool

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Parameters: corePoolSize - the number of threads to keep in the pool, even if they are idle. Returns: a newly created scheduled thread pool

我不明白的是,corePoolSize 和 nThreads 是一回事吗?调度线程池真的是固定线程池的子集吗,也就是说我可以把调度线程池当成固定线程池,可以对延迟任务进行排队?

最佳答案

是的,它们基本上是一样的,只是增加了调度功能。 ScheduledThreadPoolExecutor 甚至扩展了 ExecutorService (ThreadPoolExecutor) 的默认实现。

nThreads 和 corePoolSize 是要生成的线程数。对于一个固定的执行者来说,它总是一样的。对于其他实现,它在最小值 (corePoolSize) 和最大值 (maxPoolSize) 之间变化。

关于java固定线程池和定时线程池的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037693/

相关文章:

c++ - thread::hardware_concurrency() 作为模板参数

无限迭代器上的Python线程/进程池?

java - Spring Context 启动时打印应用程序横幅

java - Swagger (Springfox) 仅查找 Controller @RequestBody (Spring Boot) 中使用的模型

java - parallelStream中HashSet的线程安全

c++ - C++应用多线程中的Lock方法

java - 根据文本更改 TextView 颜色

java - 在 Web 应用程序中使用 log4j.xml 未生成日志文件

node.js - 如何在 Node.js 中的两个工作线程之间创建直接通信 channel

c# - 为什么这个 C# ThreadPool 有时会丢弃工作项?