Java 定时线程池各个方法的区别 Java周期执行线程池各个方法的区别 ScheduledExecutorService schedulerService

2023-05-16

Java 定时线程池各个方法的区别 Java周期执行线程池各个方法的区别 ScheduledExecutorService schedulerService

一、概述

        Java JDK提供的java.util.concurrent.Executors 线程池工具类中,有四个线程池创建的方法,分别是:

  • newFixedThreadPool  (固定数目线程的线程池)
  • newCachedThreadPool (可缓存线程的线程池)
  • newSingleThreadExecutor (单线程的线程池)
  • newScheduledThreadPool (定时及周期执行的线程池)

        本文将整理 newScheduledThreadPool 定时线程池中各个方法的区别。

二、方法区别

        1、scheduler , 无返回值

/**
 * Description: schedule 方法,只执行一次 , 没有返回值
 * @param executor
 * @return  void
 * @version v1.0
 * @author wu
 * @date 2023/2/27 22:27
 */
public static void schedulerNoReturn(ScheduledExecutorService executor){
    // 1、schedule 方法,只执行一次 , 没有返回值
    executor.schedule(()->{
        System.out.println("schedulerNoReturn ==");
    },1, TimeUnit.SECONDS);
}

        2、scheduler , 有返回值

/**
 * Description: schedule 方法,只执行一次 , 没有返回值
 * @param executor
 * @return  void
 * @version v1.0
 * @author wu
 * @date 2023/2/27 22:27
 */
public static String schedulerYesReturn(ScheduledExecutorService executor) throws ExecutionException, InterruptedException {
    // 1、schedule 方法,只执行一次 , 没有返回值
    final ScheduledFuture<String> future = executor.schedule(() -> {
        System.out.println("schedulerYesReturn ==");
        return DateUtils.getDateTime();
    }, 1, TimeUnit.SECONDS);
    return future.get();
}

        3、固定时间执行: scheduleAtFixedRate --- 延迟5秒测试

/**
 * Description: 固定时间执行 , 和当前任务是否执行完毕 无关
 * @param executor
 * @param expireTime --- 过期时间,单位:秒
 * @return  void
 * @version v1.0
 * @author wu
 * @date 2023/2/27 22:39
 */
public static void scheduleAtFixedRateTest(ScheduledExecutorService executor , long expireTime){
    // 2、固定时间执行 , 每隔5s 执行一次 。 sleep > delay 时,以 sleep 为准
    // sleep < delay , 以 delay  为准
    executor.scheduleAtFixedRate(()->{
        try {
            TimeUnit.SECONDS.sleep(expireTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("scheduleAtFixedRate ===·"+ DateUtils.getDateTime());
    },1,5,TimeUnit.SECONDS);
}

        3.1、测试 - 固定执行时间5s :


        scheduleAtFixedRateTest(executor,4L); // 小于
        scheduleAtFixedRateTest(executor,5L); // 等于
        scheduleAtFixedRateTest(executor,6L); // 大于
        

        3.2、测试结果分别如下:

--- 方法执行时间为: 4s 
scheduleAtFixedRate ===·2023-03-26 19:34:19
scheduleAtFixedRate ===·2023-03-26 19:34:24
scheduleAtFixedRate ===·2023-03-26 19:34:29
scheduleAtFixedRate ===·2023-03-26 19:34:34

--- 方法执行时间为: 5s 
scheduleAtFixedRate ===·2023-03-26 19:36:02
scheduleAtFixedRate ===·2023-03-26 19:36:07
scheduleAtFixedRate ===·2023-03-26 19:36:12
scheduleAtFixedRate ===·2023-03-26 19:36:17

--- 方法执行时间为: 6s 
scheduleAtFixedRate ===·2023-03-26 19:39:04
scheduleAtFixedRate ===·2023-03-26 19:39:10
scheduleAtFixedRate ===·2023-03-26 19:39:16
scheduleAtFixedRate ===·2023-03-26 19:39:22

        4、固定时间执行+延迟时间后,再执行 : scheduleWithFixedDelay

/**
 * Description: 固定时间执行,当前任务执行完毕后,再间隔 delay 秒后执行
 * @param executor
 * @param expireTime --- 过期时间,单位:秒
 * @return  void
 * @version v1.0
 * @author wu
 * @date 2023/2/27 22:41
 */
public static void scheduleWithFixedDelayTest(ScheduledExecutorService executor , long expireTime){
    // 3、固定时间执行,当前任务执行完毕后,再间隔 delay 秒后执行
    //  下次执行时间为: sleep + delay
    executor.scheduleWithFixedDelay(()->{
        try {
            TimeUnit.SECONDS.sleep(expireTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("scheduleWithFixedDelay ===·"+ DateUtils.getDateTime());
    },1,5,TimeUnit.SECONDS);
}

        4.1、测试 - 固定执行时间5s :


        scheduleWithFixedDelayTest(executor,4L); // 小于
        scheduleWithFixedDelayTest(executor,5L); // 等于
        scheduleWithFixedDelayTest(executor,6L); // 大于
        

        4.2、测试结果分别如下:

--- 方法执行时间为: 4s 
scheduleWithFixedDelay ===·2023-03-26 19:44:11
scheduleWithFixedDelay ===·2023-03-26 19:44:20
scheduleWithFixedDelay ===·2023-03-26 19:44:29
scheduleWithFixedDelay ===·2023-03-26 19:44:38


--- 方法执行时间为: 5s 
scheduleWithFixedDelay ===·2023-03-26 19:46:00
scheduleWithFixedDelay ===·2023-03-26 19:46:10
scheduleWithFixedDelay ===·2023-03-26 19:46:20
scheduleWithFixedDelay ===·2023-03-26 19:46:30

--- 方法执行时间为: 6s
scheduleWithFixedDelay ===·2023-03-26 19:47:33
scheduleWithFixedDelay ===·2023-03-26 19:47:44
scheduleWithFixedDelay ===·2023-03-26 19:47:55
scheduleWithFixedDelay ===·2023-03-26 19:48:06
 

三、总结

        1、定时线程池中,四个方法位于 ScheduledExecutorService 类中

public ScheduledFuture<?> schedule(Runnable command,
                                   long delay, TimeUnit unit);

public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                       long delay, TimeUnit unit);
                                       
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                              long initialDelay,
                                              long period,
                                              TimeUnit unit);
                                              
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                 long initialDelay,
                                                 long delay,
                                                 TimeUnit unit);
                                                 
                                       

 

 

        2、schedule 的两个方法特点是:

                只执行一次,可以根据实际需要,有返回值和无返回值。

        3、scheduleAtFixedRate :

                固定速率执行, 当方法执行时间 > period 时,则会按照 方法执行时间 周期的速率进行执行 ; 当方法执行时间 <= period 时,则按照 period 周期速率执行。 【二 - 3.2、测试结果分别如下】

        4、scheduleWithFixedDelay :

                固定速率执行,执行的周期速率为:方法执行时间 + period 。 【二 - 4.2、测试结果分别如下】

        5、scheduleAtFixedRate 和 scheduleWithFixedDelay 区别:

  • scheduleAtFixedRate : 方法执行时间 > period ,会按照 方法执行时间 周期执行。 
  • scheduleWithFixedDelay : 方法执行完毕后,等待 period 时间后,再次执行。

        6、完整的测试代码

public static void main(String[] args) throws ExecutionException, InterruptedException {
        final ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
        System.out.println(Thread.currentThread().getName()+" === start ," +DateUtils.getDateTime());

        // 1、scheduler ,无返回值测试
//        schedulerNoReturn(executor);

        // 2、scheduler ,有返回值测试
//        final String s = schedulerYesReturn(executor);
//        System.out.println("scheduler ,有返回值测试:"+s);

        // 3、、固定时间执行  expireTime > delay 时,以 period 为准
//        scheduleAtFixedRateTest(executor,4L); // 小于
//        scheduleAtFixedRateTest(executor,5L); // 等于
//        scheduleAtFixedRateTest(executor,6L); // 大于

        // 4、固定时间执行,当前任务执行完毕后,再间隔 delay 秒后执行
//        scheduleWithFixedDelayTest(executor,4L); // 小于
//        scheduleWithFixedDelayTest(executor,5L); // 等于
        scheduleWithFixedDelayTest(executor,6L); // 大于

        System.out.println(Thread.currentThread().getName()+" === end , "+DateUtils.getDateTime());

    }
    

参考资料: Java 多线程 Runnable 与 Callable 接口的区别

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 定时线程池各个方法的区别 Java周期执行线程池各个方法的区别 ScheduledExecutorService schedulerService 的相关文章

  • CCF推荐国际学术会议和期刊目录2019年

    链接 xff1a 全目录下载地址
  • 2022教资押题

    1 试题类型 2 具体文件夹 3 百度网盘链接 xff1a 链接 xff1a https pan baidu com s 17ZlLeE2E8Rzz7ELHptE8Fg 提取码 xff1a 9vky
  • 强化学习Q-learning入门教学

    1 问题描述 2 图形化展示 3 reward矩阵构建 4 Q表构建 这里需要说明的是Q表的转移规则原本是 xff1a 本例中为了方便介绍 xff0c 将 值设为1了 原文讲解的通俗易懂 xff0c 有兴趣的可以看一下 出处 xff1a h
  • 英文文献代码查找

    原文链接 xff1a https blog csdn net weixin 45656790 article details 109271019
  • Word中插入集合和元素的包含符号

    1 比较简单 xff0c 是元素和集合的包含关系 查找 xff1a word gt 插入 gt 符号栏下拉 xff0c 选择基础数学 2 集合间的包含关系 四个数字 xff0c 代表一个 输入文档中的指定位置 xff0c 选中数字以后 xf
  • 微信PC端聊天界面表情包无法显示

    我试成功的一个办法 xff0c 分享一下 具体步骤 xff1a 1 找到微信聊天界面的设置选项 xff0c 如图 2 进入微信文件保存位置 3 进入WeChat Files All Users config目录 4 删除config dat
  • MathType 提示需要一个新版本的MT Extra(True Type)字体

    1 打开C Windows Fonts文件夹 xff0c 若里面有MT Extra TrueType 字体或其快捷方式 xff0c 则将其删除 2 找到MathType安装目录下C Program Files x86 MathType Fo
  • Word快捷键设置上下标;Word取消表格虚线;Word查找数学符号

    问题1 快捷键设置上下角标 这个在论文写作时比较常用 xff0c 本人也是最近在写大论文 xff0c 遇到了这个情况 Word和Visio中 xff0c 都可以使用 步骤 xff1a 选中即将成为上下标的内容 xff0c 上标快捷键 xff
  • xcode中xib使用之轻松学习

    1 创建xib文件 在工程目录中New Files xff0c 选择user interface类型中的empty创建一个空的interface builder document文件 文件名没有强制的要求 xff0c 最好使用 前缀 xff
  • 用Opencv打造一台自动视觉目标跟踪系统

    平移 倾斜伺服装置 xff0c 帮助摄像机使用视觉自动跟踪颜色对象 简介 现在我们将使用我们的设备帮助相机自动跟踪颜色对象 xff0c 如下所示 xff1a OpenCV可免费用于学术和商业用途 它具有C 43 43 xff0c C xff
  • error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools"【转载+修改】

    error Microsoft Visual C 43 43 14 0 is required Get it with Microsoft Visual C 43 43 Build Tools http landinghub visuals
  • 如何使用OpenCV实现多张图像拼接

    先来看看OpenCV官方的例子得到效果是非常的好 xff0c 输入的images如下 xff1a 效果 xff1a Stitcher类与detail命名空间 OpenCV提供了高级别的函数封装在Stitcher类中 xff0c 使用很方便
  • 如何使用OpenCV对物体进行搜索检测与识别

    在本教程中 xff0c 我们将了解对象检测中称为 选择性搜索 的重要概念 我们还将用C 43 43 和Python共享OpenCV代码 物体检测与物体识别 对象识别算法识别图像中存在哪些对象 它将整个图像作为输入 xff0c 并输出该图像中
  • 一种基于深度学习的方法来检测摩托车头盔的使用

    背景 据统计使用摩托车头盔可以将道路交通事故中摩托车驾驶员致命伤害的可能性降低42 xff05 xff0c 尽管如此 xff0c 遵守摩托车头盔还是较少 xff0c 尤其是在发展中国家 xff0c 为了有效开展针对性的头盔使用运动 xff0
  • 偏振光相机1——偏振光

    光的电磁波属性 光是一种电磁波 xff0c 这个概念大家应该不陌生 既然是电磁波 xff0c 那我们从电磁波的特性上来看它有哪些属性 用图1中的交变电磁场来描述光的特性 xff0c 电场和磁场在空间中相互垂直 xff0c 它们同时与光的传播
  • 偏振光相机2——索尼大法

    Stokes参量 在上一篇 偏振光相机 偏振光 中 xff0c 我们知道偏振光有线性偏振光 椭圆偏振光 圆偏光 那么如何定量的描述偏振光呢 xff1f Stokes矢量是一种广泛用来描述偏振光属性的方法 图1 不同类型的偏振光 线性偏振光和
  • 偏振光相机3——偏振应用

    在之前的2篇中 xff0c 介绍了偏振光的基本概念和基于SONY最新CMOS偏振传感器芯片的相机 在本篇中 xff0c 我们来看看偏振相机的一些应用 偏振相机的应用离不开偏振光 xff0c 那么先看看如何得到偏振光信息 如何获取偏光 在 偏
  • 【干货】生成对抗网络GANs算法在医学图像领域应用总结

    Goodfellow等人 介绍了生成对抗网络 xff08 GAN xff09 以模拟数据分布 由于与两个基本属性相关的原因 xff0c GAN可以合成真实图像 GAN是一种无监督的训练方法 xff0c 可以通过类似于人类学习图像特征的方式获
  • 图像算法之3D人脸识别技术原理概述

    随着深度学习技术的进步 xff0c 面部相关任务的研究也成为学术界和工业界的热门话题 众所周知的面部任务通常包括面部检测 xff0c 面部识别 xff0c 面部表情识别等 xff0c 其主要使用2D RGB面部 xff08 通常包括一些纹理
  • 如何使用OpenCV计算机视觉检测帕金森病图片

    在本教程中 xff0c 您将学习如何使用OpenCV和机器学习在手绘的螺旋和波浪图像中自动检测帕金森病 本教程来自来自巴西的博士生Joao Joao有兴趣利用计算机视觉和机器学习基于几何图形 xff08 即螺旋和符号波 xff09 自动检测

随机推荐