ScheduledExecutorService和while(true) sleep 两种定时方式的定时间隔准确度比较

为什么会有这篇博客呢?因为最近朋友新入职了一家公司,公司要求他对现有的代码进行优化,其中就涉及到了定时任务。原有的方式是while(true) sleep,而我朋友找到了另外一种定时方式,即ScheduledExecutorService。他很疑惑,不知道原有的while(true) sleep的方式定时间隔准确度好,还是他现在找的ScheduledExecutorService这种方式定时间隔准确度好。这时他找到了我,让我帮他解答这个问题,于是就有了这篇博客。

我们分别编写while(true) sleep 定时方式的代码和ScheduledExecutorService定时方式的代码,我们分别让两种方式50毫秒执行一次,打印时间间隔
while(true) sleep 定时方式
    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        while(true){
            Thread.sleep(50);
            long endTime = System.currentTimeMillis();
            System.out.println(System.currentTimeMillis() - startTime);
            startTime = endTime;
        }
    }
ScheduledExecutorService 定时方式
    public static void main(String[] args) {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
        final long[] startTime = {System.currentTimeMillis()};
        executorService.scheduleWithFixedDelay(()->{
           long endTime = System.currentTimeMillis();
            System.out.println(endTime - startTime[0]);
            startTime[0] = endTime;
        },50,50, TimeUnit.MILLISECONDS);
    }
接着分别运行两个main方法,效果如下:
while(true) sleep 定时方式执行效果

在这里插入图片描述

ScheduledExecutorService 定时方式执行效果

在这里插入图片描述

我们能观察到while(true) sleep 定时方式最大执行间隔时间为51毫秒,而ScheduledExecutorService 定时方式最大执行间隔时间为52毫秒。

由此可以我们可以得出结论: while(true) sleep 定时方式定时时间准确度更高 。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ScheduledExecutorService是Java中用于定时执行任务的接口。它是ExecutorService的子接口,提供了在指定的延迟后执行任务或定期执行任务的功能。 使用ScheduledExecutorService可以创建一个线程池,其中的线程可以按照指定的时间间隔执行任务。它提供了以下几种常用的方法: 1. schedule(Runnable command, long delay, TimeUnit unit):在指定的延迟时间后执行任务。 2. schedule(Callable<V> callable, long delay, TimeUnit unit):在指定的延迟时间后执行任务,并返回一个可以获取执行结果的Future对象。 3. scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit):在指定的初始延迟后开始执行任务,并以固定的时间间隔重复执行。 4. scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit):在指定的初始延迟后开始执行任务,并在每次执行完成后,等待指定的延迟时间后再次执行。 下面是一个简单示例: ```java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledTaskExample { public static void main(String[] args) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // 延迟5秒后执行任务 executor.schedule(() -> { System.out.println("任务执行"); }, 5, TimeUnit.SECONDS); // 初始延迟2秒,每隔3秒重复执行任务 executor.scheduleAtFixedRate(() -> { System.out.println("定期执行任务"); }, 2, 3, TimeUnit.SECONDS); // 等待一段时间后关闭线程池 try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } executor.shutdown(); } } ``` 上述示例代码创建了一个ScheduledExecutorService线程池,其中包含一个线程。通过schedule方法和scheduleAtFixedRate方法分别定义了两个定时任务,并在一段时间后关闭了线程池。 注意,在使用ScheduledExecutorService时,需要手动调用shutdown方法来关闭线程池,以释放资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值