Executors执行器newScheduledThreadPool方法示例

x33g5p2x  于2022-10-06 转载在 其他  
字(2.3k)|赞(0)|评价(0)|浏览(747)

在本教程中,我们将学习Executor的newScheduledThreadPoolfactory方法。

Executors.newScheduledThreadPool方法

该方法创建了一个线程池,可以安排命令在给定的延迟后运行或定期执行。

newScheduledThreadPool方法返回ScheduledExecutorServiceinterface
ScheduledExecutorService接口提供 schedule()方法创建具有各种延迟的任务,并返回一个可用于取消或检查执行的任务对象。scheduleAtFixedRate()scheduleWithFixedDelay()方法创建并执行周期性运行的任务,直到取消。

使用Executor.execute(Runnable)ExecutorServicesubmit方法提交的命令被安排在一个要求的延迟为零的地方。在计划方法中也允许零和负延迟(但不是周期),并被视为立即执行的请求。
让我们通过一个例子来理解ScheduledExecutorService Interface和newScheduledThreadPool()工厂方法的方法。

  1. public class SchedulingTasksWithScheduledThreadPool {
  2. public static void main(String[] args) throws InterruptedException {
  3. System.out.println("Thread main started");
  4. // Create a task
  5. Runnable task1 = () -> {
  6. System.out.println("Executing the task1 at: " + new Date());
  7. };
  8. // Create a task
  9. Runnable task2 = () -> {
  10. System.out.println("Executing the task2 at: " + new Date());
  11. };
  12. ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
  13. System.out.println("Scheduling task to run after 5 seconds... " + new Date());
  14. scheduledExecutorService.schedule(task1, 5, TimeUnit.SECONDS);
  15. scheduledExecutorService.schedule(task2, 5, TimeUnit.SECONDS);
  16. scheduledExecutorService.shutdown();
  17. System.out.println("Thread main finished");
  18. }
  19. }

输出:

  1. Thread main started
  2. Scheduling task to run after 5 seconds... Sat Sep 01 10:56:40 IST 2018
  3. Thread main finished
  4. Executing the task1 at: Sat Sep 01 10:56:45 IST 2018
  5. Executing the task2 at: Sat Sep 01 10:56:45 IST 2018

*scheduledExecutorService.schedule()*函数接收一个Runnable,一个延迟值,以及延迟的单位。上面的程序在提交后的5秒后执行任务。
现在让我们看看一个例子,我们定期执行任务 --

  1. public class SchedulingTasksWithScheduledThreadPool {
  2. public static void main(String[] args) throws InterruptedException {
  3. System.out.println("Thread main started");
  4. ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
  5. // Create a task
  6. Runnable task1 = () -> {
  7. System.out.println("Executing the task1 at: " + new Date());
  8. };
  9. scheduledExecutorService.scheduleAtFixedRate(task1, 0, 2, TimeUnit.SECONDS);
  10. System.out.println("Thread main finished");
  11. }
  12. }

输出:

  1. Thread main started
  2. Thread main finished
  3. Executing the task1 at: Sat Sep 01 11:03:16 IST 2018
  4. Executing the task1 at: Sat Sep 01 11:03:18 IST 2018
  5. Executing the task1 at: Sat Sep 01 11:03:20 IST 2018
  6. Executing the task1 at: Sat Sep 01 11:03:22 IST 2018
  7. Executing the task1 at: Sat Sep 01 11:03:24 IST 2018
  8. ......

相关文章