简体   繁体   English

如何使用 ExecutorService 调度多个任务

[英]How to schedule multiple tasks with ExecutorService

I have three independend tasks to be executed at every 1 minute.我每 1 分钟要执行三个独立的任务。 Here I have developed two options.在这里,我开发了两个选项。

Option1选项1

ScheduledExecutorService service1 = Executors.newScheduledThreadPool(1); 
ScheduledExecutorService service2 = Executors.newScheduledThreadPool(1); 
ScheduledExecutorService service2 = Executors.newScheduledThreadPool(1); 
service1.scheduleAtFixedRate(new task1(), 0, 60, TimeUnit.SECONDS); 
service2.scheduleAtFixedRate(new task2(), 0, 60, TimeUnit.SECONDS); 
service3.scheduleAtFixedRate(new task3(), 0, 60, TimeUnit.SECONDS);

Option2选项2

ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
service.scheduleAtFixedRate(new task1(), 0, 60, TimeUnit.SECONDS);
service.scheduleAtFixedRate(new task2(), 0, 60, TimeUnit.SECONDS);
service.scheduleAtFixedRate(new task3(), 0, 60, TimeUnit.SECONDS);

My question is which option is preferred?我的问题是哪个选项是首选? Does Option1 consume more system resources? Option1 是否消耗更多的系统资源?

I don't know the implementation details to give an exact answer as to which usage would consume more system resources.我不知道实现细节以给出关于哪种使用会消耗更多系统资源的确切答案。 But the second option is definitely the way which is supported by Javadoc, tutorials, etc. There are some reasons which I can point out.但是第二个选项绝对是 Javadoc、教程等支持的方式。我可以指出一些原因。 First, the ScheduledExecutorService interface exposes the ability to schedule multiple tasks with a single service.首先, ScheduledExecutorService接口公开了使用单个服务调度多个任务的能力。

There is also a reason to not use the first option.不使用第一个选项也是有原因的。 You were trying to schedule three tasks using three separate executors.您试图使用三个单独的执行程序来安排三个任务。 But there is no guarantee that all three tasks would begin at the same time, but the executors are different and could be spun up at different times.但是不能保证所有三个任务都会同时开始,但是执行者是不同的,可以在不同的时间启动。 On the other hand, if you used a single executor service the three tasks should be started concurrently.另一方面,如果您使用单个执行程序服务,则应同时启动三个任务。

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

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