gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:06:18 25 4
gpt4 key购买 nike

我有一个固定的线程池,随时运行 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com