计算机系统应用教程网站

网站首页 > 技术文章 正文

Java定时任务之ScheduledThreadPoolExecutor

btikc 2024-11-21 10:54:06 技术文章 52 ℃ 0 评论

ScheduledThreadPoolExecutor是JDK5提供的可执行定时任务的一个工具类,可以在多线程环境下延迟执行任务或者定期执行任务;和Timer类似,它也提供了三种定时模式:

  1. 延迟执行任务
  2. 固定延迟的定期执行(fixed delay)
  3. 按照固定的周期执行(fixed rate)

延迟执行任务

任务将按照给定的时间延迟delay后开始执行;对应的方法如下:

schedule(Runnable command, long delay, TimeUnit unit)  
schedule(Callable<V> callable, long delay, TimeUnit unit)  

下面我们通过一个例子检验下结果是否正确:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        PrintUtil.print("start schedule a task.");
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                PrintUtil.print("task is running.");
            }
}, 5, TimeUnit.SECONDS);

我们计划了一个5秒钟后执行的任务,通过打印结果可以看到确实按照给定时间执行了:

15:44:07--start schedule a task.
15:44:12--task is running.

固定延迟的定期执行

任务第一次按照给定的初始延迟initialDelay执行,后续每一次执行的时间为上一次任务的结束时间加上给定的period后执行;对应的方法如下:

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

同样我们通过一个例子检验下结果是否正确:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        PrintUtil.print("start schedule a task.");
        executor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                PrintUtil.print("task is running.");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
}, 0, 5, TimeUnit.SECONDS);

我们计划了一个定期(每5秒钟)延迟执行的任务,第一次任务立即执行,每次任务执行时长2秒钟,通过打印的日志我们可以看到每次任务开始执行的时间为:上次任务结束时间+5秒钟:

15:55:16--start schedule a task.
15:55:16--task is running.
15:55:18--task is finished.
15:55:23--task is running.
15:55:25--task is finished.
15:55:30--task is running.
15:55:32--task is finished.

按照固定的周期执行

任务第一次按照给定的初始延迟initialDelay执行,后续每一次执行的时间为固定的时间间隔period,如果线程池中工作线程不够则任务顺延执行;对应的方法如下:

scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit)

同样我们通过一个例子检验下结果是否正确:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
        PrintUtil.print("start schedule a task.");
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                PrintUtil.print("task is running.");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                PrintUtil.print("task is finished.");
            }
}, 0, 5, TimeUnit.SECONDS);

我们创建了一个核心线程池为10的ScheduledThreadPoolExecutor,并计划了一个定期(每5秒钟)执行一次的任务,过打印的日志我们可以看到每次任务开始执行的时间为:上次任务开始时间+5秒钟:

16:02:43--start schedule a task.
16:02:43--task is running.
16:02:45--task is finished.
16:02:48--task is running.
16:02:50--task is finished.


上面的例子都是计划了一个任务,如果是有多个定时任务同时执行会怎么样呢?

如果线程足够并且CPU资源足够,那就会同时执行,如果线程或者CPU资源不够那只能排队执行了。有兴趣的话可以克隆文末的测试代码,里面提供了一些测试的例子。

底层原理

ScheduledThreadPoolExecutor是如何保证我们计划的任务都是按照正确的时间点执行的呢?

其内部实现了一个阻塞队列DelayedWorkQueue,所有的任务都会放到这个队列里。这个阻塞队列内部通过一个数组来保存这些任务,并且基于最小堆排序,按照每个任务的下次执行时间进行排序,这样就保证了执行线程拿到的这个队列中的第一个元素就是最接近当前时间执行的任务了。

相关的源码如下:

// 保存定时任务的队列
private RunnableScheduledFuture<?>[] queue = new RunnableScheduledFuture<?>[INITIAL_CAPACITY];
// 最小堆排序相关的方法
private void siftUp(int k, RunnableScheduledFuture<?> key)
private void siftDown(int k, RunnableScheduledFuture<?> key)

那时间上是如何保证的呢?

DelayedWorkQueue重写了take和poll方法,利用了AQS的ConditionObject机制使当前线程休眠,等时间到了再唤醒线程去拿第一个任务。

关于AQS和ConditonObject的介绍,可以参考下文末的链接。

public RunnableScheduledFuture<?> take() throws InterruptedException {
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                for (;;) {
                    RunnableScheduledFuture<?> first = queue[0];
                    if (first == null)
                        available.await();
                    else {
                        long delay = first.getDelay(NANOSECONDS);
                        if (delay <= 0)
                            return finishPoll(first);
                        first = null; // don't retain ref while waiting
                        if (leader != null)
                            available.await();
                        else {
                            Thread thisThread = Thread.currentThread();
                            leader = thisThread;
                            try {
                                available.awaitNanos(delay);
                            } finally {
                                if (leader == thisThread)
                                    leader = null;
                            }
                        }
                    }
                }
            } finally {
                if (leader == null && queue[0] != null)
                    available.signal();
                lock.unlock();
            }
}

优点

作为对JDK1.3推出的Timer的替代,ScheduledThreadPoolExecutor有如下优点:

  1. 它支持多个定时任务同时执行,而Timer是单线程执行的
  2. 它通过System.nanoTime()保证了任务执行时间不受操作系统时间变化的影响
  3. 一个定时任务抛出异常,其他定时任务不受影响,而Timer却不支持这一点

Demo代码

src/main/java/net/weichitech/util/ScheduledThreadPoolExecutorDemo.java · 小西学编程/java-learning - Gitee.com

参考文章

Java定时任务之Timer原理解析

JAVA并发之ReentrantLock原理解析

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表