百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

Java定时调度机制 - ScheduledExecutorService

yuyutoo 2024-10-12 00:07 16 浏览 0 评论

我们知道,Java的定时调度可以通过Timer&TimerTask来实现。由于其实现的方式为单线程,因此从JDK1.3发布之后就一直存在一些问题,大致如下:

  1. 多个任务之间会相互影响
  2. 多个任务的执行是串行的,性能较低

ScheduledExecutorService在设计之初就是为了解决Timer&TimerTask的这些问题。因为天生就是基于多线程机制,所以任务之间不会相互影响(只要线程数足够。当线程数不足时,有些任务会复用同一个线程)。

除此之外,因为其内部使用的延迟队列,本身就是基于等待/唤醒机制实现的,所以CPU并不会一直繁忙。同时,多线程带来的CPU资源复用也能极大地提升性能。

如何使用

基本作用

因为ScheduledExecutorService继承于ExecutorService,所以本身支持线程池的所有功能。额外还提供了4种方法,我们来看看其作用。

/**
 * 带延迟时间的调度,只执行一次
 * 调度之后可通过Future.get()阻塞直至任务执行完毕
 */
1. public ScheduledFuture<?> schedule(Runnable command,
 long delay, TimeUnit unit);
/**
 * 带延迟时间的调度,只执行一次
 * 调度之后可通过Future.get()阻塞直至任务执行完毕,并且可以获取执行结果
 */
2. public <V> ScheduledFuture<V> schedule(Callable<V> callable,
 long delay, TimeUnit unit);
/**
 * 带延迟时间的调度,循环执行,固定频率
 */
3. public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
 long initialDelay,
 long period,
 TimeUnit unit);
/**
 * 带延迟时间的调度,循环执行,固定延迟
 */
4. public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
 long initialDelay,
 long delay,
 TimeUnit unit);

1. schedule Runnable

该方法用于带延迟时间的调度,只执行一次。调度之后可通过Future.get()阻塞直至任务执行完毕。我们来看一个例子。

@Test public void test_schedule4Runnable() throws Exception {
 ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
 ScheduledFuture future = service.schedule(() -> {
 try {
 Thread.sleep(3000L);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 System.out.println("task finish time: " + format(System.currentTimeMillis()));
 }, 1000, TimeUnit.MILLISECONDS);
 System.out.println("schedule finish time: " + format(System.currentTimeMillis()));
 System.out.println("Runnable future's result is: " + future.get() +
 ", and time is: " + format(System.currentTimeMillis()));
}

上述代码达到的效果应该是这样的:延迟执行时间为1秒,任务执行3秒,任务只执行一次,同时通过Future.get()阻塞直至任务执行完毕。

我们运行看到的效果的确和我们猜想的一样,如下图所示。

2. schedule Callable

在schedule Runnable的基础上,我们将Runnable改为Callable来看一下。

@Test public void test_schedule4Callable() throws Exception {
 ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
 ScheduledFuture<String> future = service.schedule(() -> {
 try {
 Thread.sleep(3000L);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 System.out.println("task finish time: " + format(System.currentTimeMillis()));
 return "success";
 }, 1000, TimeUnit.MILLISECONDS);
 System.out.println("schedule finish time: " + format(System.currentTimeMillis()));
 System.out.println("Callable future's result is: " + future.get() +
 ", and time is: " + format(System.currentTimeMillis()));
}

运行看到的结果和Runnable基本相同,唯一的区别在于future.get()能拿到Callable返回的真实结果。

3. scheduleAtFixedRate

该方法用于固定频率地对一个任务循环执行,我们通过一个例子来看看效果。

@Test public void test_scheduleAtFixedRate() {
 ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
 service.scheduleAtFixedRate(() -> {
 try {
 Thread.sleep(3000L);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 System.out.println("task finish time: " + format(System.currentTimeMillis()));
 }, 1000L, 1000L, TimeUnit.MILLISECONDS);
 System.out.println("schedule finish time: " + format(System.currentTimeMillis()));
 while (true) {
 }
}

在这个例子中,任务初始延迟1秒,任务执行3秒,任务执行间隔为1秒。我们来看看执行结果:

4. scheduleWithFixedDelay

该方法用于固定延迟地对一个任务循环执行,我们通过一个例子来看看效果。

@Test public void test_scheduleWithFixedDelay() {
 ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
 service.scheduleWithFixedDelay(() -> {
 try {
 Thread.sleep(3000L);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 System.out.println("task finish time: " + format(System.currentTimeMillis()));
 }, 1000L, 1000L, TimeUnit.MILLISECONDS);
 System.out.println("schedule finish time: " + format(System.currentTimeMillis()));
 while (true) {
 }
}

在这个例子中,任务初始延迟1秒,任务执行3秒,任务执行间隔为1秒。我们来看看执行结果:

5. scheduleAtFixedRate和scheduleWithFixedDelay的区别

既然这两个方法都是对任务循环执行,那么他们又有何区别呢?通过jdk文档我们找到了答案。


直白地讲,scheduleAtFixedRate()为固定频率,scheduleWithFixedDelay()为固定延迟。固定频率是相对于任务执行的开始时间,而固定延迟是相对于任务执行的结束时间,这就是他们最根本的区别!

另外,从3和4的运行结果也能看出这些差异。

源码阅读初体验

一般源码的入口在于构造方法,我们来看看。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
 return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
 super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
 new DelayedWorkQueue());
}

在构造方法中我们看到以下信息:

  1. ScheduledThreadPoolExecutor构造方法最终调用的是ThreadPoolExecutor构造方法
  2. 阻塞队列使用的是DelayedWorkQueue

上述信息的第2点至关重要,但是限于篇幅,本文将不做深入分析。

接下来我们看看scheduleWithFixedDelay()方法,主要做了3件事情:

  1. 入参校验,包括空指针、数字范围
  2. 将Runnable包装成RunnableScheduledFuture
  3. 延迟执行RunnableScheduledFuture
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
 long initialDelay,
 long delay,
 TimeUnit unit) {
 // 1. 入参校验,包括空指针、数字范围
 if (command == null || unit == null)
 throw new NullPointerException();
 if (delay <= 0)
 throw new IllegalArgumentException();
 // 2. 将Runnable包装成`RunnableScheduledFuture`
 ScheduledFutureTask<Void> sft =
 new ScheduledFutureTask<Void>(command,
 null,
 triggerTime(initialDelay, unit),
 unit.toNanos(-delay));
 RunnableScheduledFuture<Void> t = decorateTask(command, sft);
 sft.outerTask = t;
 // 3. 延迟执行`RunnableScheduledFuture`
 delayedExecute(t);
 return t;
}

delayedExecute()这个方法从字面描述来看是延迟执行的意思,我们深入到这个方法里面去看看。

private void delayedExecute(RunnableScheduledFuture<?> task) {
 // 1. 线程池运行状态判断
 if (isShutdown())
 reject(task);
 else {
 // 2. 将任务添加到队列
 super.getQueue().add(task);
 // 3. 如果任务添加到队列之后,线程池状态变为非运行状态,
 // 需要将任务从队列移除,同时通过任务的`cancel()`方法来取消任务
 if (isShutdown() &&
 !canRunInCurrentRunState(task.isPeriodic()) &&
 remove(task))
 task.cancel(false);
 // 4. 如果任务添加到队列之后,线程池状态是运行状态,需要提前启动线程
 else
 ensurePrestart();
 }
}

在线程池状态正常的情况下,最终会调用ensurePrestart()方法来完成线程的创建。主要逻辑有两个:

  1. 当前线程数未达到核心线程数,则创建核心线程
  2. 当前线程数已达到核心线程数,则创建非核心线程,不会将任务放到阻塞队列中,这一点是和普通线程池是不相同的
/**
 * Same as prestartCoreThread except arranges that at least one
 * thread is started even if corePoolSize is 0.
 */
void ensurePrestart() {
 int wc = workerCountOf(ctl.get());
 // 1. 当前线程数未达到核心线程数,则创建核心线程
 if (wc < corePoolSize)
 addWorker(null, true);
 // 2. 当前线程数已达到核心线程数,则创建非核心线程,
 // 2.1 不会将任务放到阻塞队列中,这一点是和普通线程池是不相同的
 else if (wc == 0)
 addWorker(null, false);
}

至此,除了DelayedWorkQueue延迟队列的源码还未分析,其他的我们都分析完了。

总结

首先,我们了解了ScheduledExecutorService的基本作用,然后在此基础上写了一些demo来做验证,得到的结果和基本作用是完全相同的。

然后,我们对其内部的实现原理和源代码做了初步的分析,知道了其和普通线程池是不同的地方在于:阻塞队列和创建线程的方式。

相关推荐

国产RISC-V终端Sipeed Lichee Console4A上架,1699元起

IT之家12月11日消息,国内著名开源硬件厂商Sipeed矽速科技推出RISC-V终端LicheeConsole4A,售价1699元(不带LM4A模块)-3299元。Li...

H3C交换机常用配置命令

1、配置主机名...

ThinkPad老版Bios中英文对应详解

ThinkPad老版Bios中文对应详解。解决方案:...

澳大利亚Console Connect与非洲数据中心达成战略合作,增强整个非洲的数据连接

据techafricanews网11月13日报道,在2024年非洲科技节上,澳大利亚ConsoleConnect与非洲数据中心共同宣布了一项具有里程碑意义的战略合作协议,该协议致力于提升非洲大陆关键...

多功能调焦 腾龙TAP-in Console延期发售

最新消息传出,腾龙TAP-inConsole(modeltap-01)多功能调焦器由于生产方面原因原本预计3月24日发售延迟至3月30日,腾龙的这款调焦器功能类似于适马的USBDock调焦底座,...

关于交换机上存在的不同接口介绍(一)

生活中常见的电子设备有很多,其中明交换机主要起到的是连接的作用,上面有非常多的接口,下面就一起来看看这些不同的接口作用是什么。1、RJ-45接口这是我们见的最多、应用最广的一种接口类型,它属于双绞线以...

颜值更高?微软新推精英版Xbox One手柄

本月,微软的XboxOne升级了更强大的版本——XboxOneEliteconsole(精英版?),升级版的控制手柄功能更强大,可以主导你的客厅;从曝光的图片上看得出,新版XboxOneE...

“全球首个”:Console Connect为全球物联网项目推出连接解决方案

据DevelopingTelecoms2月27日报道,在MWC2023上,全球网络即服务(NaaS)平台ConsoleConnect推出了“全球首个”私有连接解决方案,可帮助企业在全球范围内动态...

密码遗忘专题——Console口密码遗忘

如果忘记了Console口密码,用户可以通过以下两种方式来设置新的Console口密码:方法一:通过STelnet/Telnet登录设备修改Console口密码。...

为锐捷路由器交换机开启web和telnet,实现轻松管理

笔者上一篇文章写了关于锐捷二层交换机配置教程,那么接下来讲一下锐捷的路由交换设备配置web、telnet技巧。同样,今天的教程也是基于命令行,比较简单,适合新手小白进行学习。准备工作配置前准备:con...

C# - 类文件构成,C#基本语法,Console属性与方法 007

类文件(.cs)构成类文件主要分为引用命名空间与自己项目的命名空间...

Console OS系统帮你在PC上自由切换Windows和安卓应用

通过ConsoleOS你可以在你的PC上安装自己喜欢的安卓游戏,需要时之间切换回Windows进行其他工作,ConsoleOS能够完全利用你的PC硬件配置,该系统可以安装在PC的内置硬盘里,也可以...

交换机通过串口线console口登录设备

一、功能简介:PC端通过设备的Console口登录,实现对第一次上电的设备进行基本配置和管理。...

(每日持续更新)jdk api之Console基础、应用、实战

博主18年的互联网软件开发经验,从一名程序员小白逐步成为了一名架构师,我想通过平台将经验分享给大家,因此博主每天会在各个大牛网站点赞量超高的博客等寻找该技术栈的资料结合自己的经验,晚上进行用心精简、整...

KFC推出“真正的次世代主机”KFConsole!真4K/120帧

今天KFCGaming官方推特发布了一则“主机”宣传片,正式公布了旗下名为KFConsole的全新主机产品。并宣称:游戏的未来就在这里,介绍真正的次世代主机!根据官方介绍,本款KFC主机功能强大,支...

取消回复欢迎 发表评论: