简体   繁体   English

多个 ScheduledExecutorServices 或一个带有用于固定速率任务的 ThreadPool 的服务

[英]Multiple ScheduledExecutorServices or one with a ThreadPool for Fixed Rate Tasks

Consider a hypothetical case in which multiple tasks will run permanently in fixed rates.考虑一个假设情况,其中多个任务将以固定速率永久运行。 The number of these tasks will not change as long as the application runs.只要应用程序运行,这些任务的数量就不会改变。 For such a case, is there any difference between creating a thread pool with n tasks like this对于这种情况,创建具有 n 个任务的线程池之间有什么区别吗?

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(n);
for (int i = 0; i < n; i++) {
    executorService.scheduleAtFixedRate(job, 0, 5, TimeUnit.MINUTES);
}

and creating single executor for each task as given below?为每个任务创建单个执行程序,如下所示?

for (int i = 0; i < n; i++) {
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(job, 0, 5, TimeUnit.MINUTES);
}

If there is any difference, which one should be preferred and why?如果有任何区别,应该首选哪一个,为什么?

Note: Aside from creating multiple executor instances注意:除了创建多个执行器实例

The executor is meant to handle a pool of threads.执行器旨在处理线程池。 So you don't need to create N Executors with a single thread as you end up with N instances of executors and N threads.因此,您不需要使用单个线程创建 N 个执行程序,因为您最终会得到 N 个执行程序和 N 个线程的实例。 Just hold one Executor that handles the N threads and you saved some memory by having 1 executor and N threads.只需持有一个处理 N 个线程的 Executor,就可以通过拥有 1 个 executor 和 N 个线程来节省一些内存。

  1. The first one will create one executor with fixed number of threads.第一个将创建一个具有固定线程数的执行程序。
  2. The second one will create n executors each with single thread.第二个将创建 n 个执行程序,每个执行程序都有一个线程。

The difference is that later on you could re-configure number of threads in newScheduledThreadPool.不同之处在于,稍后您可以重新配置 newScheduledThreadPool 中的线程数。 You would not be able to change number of threads in newSingleThreadScheduledExecutor.您将无法更改 newSingleThreadScheduledExecutor 中的线程数。 Also when creating multiple executors you would end up with 5 objects instead of one (creating just one executor).此外,当创建多个执行程序时,您最终会得到 5 个对象而不是一个(只创建一个执行程序)。 Personally, I would go with 1st option.就个人而言,我会选择第一个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM