Executors执行器newScheduledThreadPool方法示例

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

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

Executors.newScheduledThreadPool方法

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

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

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

public class SchedulingTasksWithScheduledThreadPool {

 public static void main(String[] args) throws InterruptedException {
  System.out.println("Thread main started");

  // Create a task
  Runnable task1 = () -> {
   System.out.println("Executing the task1 at: " + new Date());
  };

  // Create a task
  Runnable task2 = () -> {
   System.out.println("Executing the task2 at: " + new Date());
  };

  ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);

  System.out.println("Scheduling task to run after 5 seconds... " + new Date());
  scheduledExecutorService.schedule(task1, 5, TimeUnit.SECONDS);
  scheduledExecutorService.schedule(task2, 5, TimeUnit.SECONDS);

  scheduledExecutorService.shutdown();
  System.out.println("Thread main finished");
 }
}

输出:

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

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

public class SchedulingTasksWithScheduledThreadPool {

 public static void main(String[] args) throws InterruptedException {
  System.out.println("Thread main started");

  ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

  // Create a task
  Runnable task1 = () -> {
   System.out.println("Executing the task1 at: " + new Date());
  };

  scheduledExecutorService.scheduleAtFixedRate(task1, 0, 2, TimeUnit.SECONDS);

  System.out.println("Thread main finished");
 }
}

输出:

Thread main started
Thread main finished
Executing the task1 at: Sat Sep 01 11:03:16 IST 2018
Executing the task1 at: Sat Sep 01 11:03:18 IST 2018
Executing the task1 at: Sat Sep 01 11:03:20 IST 2018
Executing the task1 at: Sat Sep 01 11:03:22 IST 2018
Executing the task1 at: Sat Sep 01 11:03:24 IST 2018
......

相关文章

微信公众号

最新文章

更多