我有一个固定的线程池,可以随时运行7个并发线程(带队列),我想把它变成一个只运行7个并发作业的调度线程池,但可以排队/安排更多.
阅读文档并没有真正帮助我..
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
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是要生成的线程数.对于固定的执行者,它始终是相同的.对于其他实现,它在min(corePoolSize)和max(maxPoolSize)之间变化.