JDK 8 ScheduledExecutorService源码详解(详细注释版)

JDK 8 ScheduledExecutorService源码详解(详细注释版)

1. ScheduledExecutorService接口源码

/*
 * ScheduledExecutorService接口扩展了ExecutorService
 * 提供了延迟执行和周期性执行任务的能力
 * 是Java定时任务调度的核心接口
 */
public interface ScheduledExecutorService extends ExecutorService {
    
    /**
     * 在给定延迟时间后执行一次任务
     * 
     * @param command 要执行的任务
     * @param delay 延迟时间
     * @param unit 时间单位
     * @return 表示挂起任务完成的ScheduledFuture对象
     * @throws RejectedExecutionException 如果任务无法被接受执行
     * @throws NullPointerException 如果command为null
     * @throws IllegalArgumentException 如果延迟时间小于0
     */
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);
    
    /**
     * 在给定延迟时间后执行一次有返回值的任务
     * 
     * @param callable 要执行的任务
     * @param delay 延迟时间
     * @param unit 时间单位
     * @param <V> 任务返回值类型
     * @return 表示挂起任务完成的ScheduledFuture对象
     * @throws RejectedExecutionException 如果任务无法被接受执行
     * @throws NullPointerException 如果callable为null
     * @throws IllegalArgumentException 如果延迟时间小于0
     */
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit);
    
    /**
     * 创建并执行一个周期性任务
     * 任务首次执行延迟initialDelay时间,之后每隔period时间执行一次
     * 如果任务执行时间超过period,则下一次执行会延迟
     * 
     * @param command 要执行的任务
     * @param initialDelay 首次执行的延迟时间
     * @param period 连续执行之间的时间间隔
     * @param unit 时间单位
     * @return 表示挂起任务完成的ScheduledFuture对象
     * @throws RejectedExecutionException 如果任务无法被接受执行
     * @throws NullPointerException 如果command为null
     * @throws IllegalArgumentException 如果initialDelay或period小于0
     */
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);
    
    /**
     * 创建并执行一个周期性任务
     * 任务首次执行延迟initialDelay时间,之后每次执行完成后等待delay时间再执行
     * 
     * @param command 要执行的任务
     * @param initialDelay 首次执行的延迟时间
     * @param delay 每次执行完成后的延迟时间
     * @param unit 时间单位
     * @return 表示挂起任务完成的ScheduledFuture对象
     * @throws RejectedExecutionException 如果任务无法被接受执行
     * @throws NullPointerException 如果command为null
     * @throws IllegalArgumentException 如果initialDelay或delay小于0
     */
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);
}

2. ScheduledFuture接口源码

/*
 * ScheduledFuture接口继承了Delayed和Future接口
 * 表示ScheduledExecutorService延迟任务的结果
 */
public interface ScheduledFuture<V> extends Delayed, Future<V> {
    // 继承Delayed接口的getDelay方法
    // 继承Future接口的所有方法
}

3. ScheduledThreadPoolExecutor核心实现类

/*
 * ScheduledThreadPoolExecutor是ScheduledExecutorService的主要实现
 * 继承自ThreadPoolExecutor,提供了定时任务调度功能
 */
public class ScheduledThreadPoolExecutor
        extends ThreadPoolExecutor
        implements ScheduledExecutorService {
    
    /*
     * 内部常量定义
     */
    private static final int RUNNING = -1 << COUNT_BITS; // 运行状态
    private static final int SHUTDOWN = 0 << COUNT_BITS; // 关闭状态
    private static final int STOP = 1 << COUNT_BITS;     // 停止状态
    
    // 序列化版本UID
    private static final long serialVersionUID = 589874809373857237L;
    
    /**
     * 用于包装Runnable和Callable任务的内部类
     * 实现了RunnableScheduledFuture接口
     */
    private class ScheduledFutureTask<V>
            extends FutureTask<V> implements RunnableScheduledFuture<V> {
        
        // 任务序列号,用于保证相同延迟时间的任务按FIFO顺序执行
        private final long sequenceNumber;
        // 任务应该执行的时间(相对于triggerTime的纳秒时间)
        private long time;
        // 周期任务的周期(纳秒)
        // 正数表示固定频率执行,负数表示固定延迟执行,0表示非周期任务
        private final long period;
        
        // 重新排队时使用的实际任务
        RunnableScheduledFuture<V> outerTask = this;
        
        // 在堆中的索引,用于快速删除
        private int heapIndex;
        
        /**
         * 构造方法 - 用于延迟执行的Runnable任务
         */
        ScheduledFutureTask(Runnable r, V result, long ns) {
            super(r, result);
            this.time = ns;
            this.period = 0;
            this.sequenceNumber = sequencer.getAndIncrement();
        }
        
        /**
         * 构造方法 - 用于延迟执行的Callable任务
         */
        ScheduledFutureTask(Callable<V> callable, long ns) {
            super(callable);
            this.time = ns;
            this.period = 0;
            this.sequenceNumber = sequencer.getAndIncrement();
        }
        
        /**
         * 构造方法 - 用于周期性任务
         */
        ScheduledFutureTask(Runnable r, V result, long ns, long period) {
            super(r, result);
            this.time = ns;
            this.period = period;
            this.sequenceNumber = sequencer.getAndIncrement();
        }
        
        /**
         * 获取任务剩余延迟时间
         * 
         * @param unit 时间单位
         * @return 剩余延迟时间
         */
        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(time - now(), NANOSECONDS);
        }
        
        /**
         * 比较两个Delayed对象的延迟时间
         * 
         * @param other 另一个Delayed对象
         * @return 比较结果
         */
        @Override
        public int compareTo(Delayed other) {
            if (other == this) // 同一个对象
                return 0;
            if (other instanceof ScheduledFutureTask) {
                ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
                long diff = time - x.time;
                if (diff < 0)
                    return -1;
                else if (diff > 0)
                    return 1;
                else if (sequenceNumber < x.sequenceNumber)
                    return -1;
                else
                    return 1;
            }
            long diff = getDelay(NANOSECONDS) - other.getDelay(NANOSECONDS);
            return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
        }
        
        /**
         * 判断是否为周期性任务
         * 
         * @return true表示是周期性任务
         */
        @Override
        public boolean isPeriodic() {
            return period != 0;
        }
        
        /**
         * 获取任务应该执行的时间
         */
        private long now() {
            return ScheduledThreadPoolExecutor.this.nanoTime();
        }
        
        /**
         * 设置下次执行时间
         */
        private void setNextRunTime() {
            long p = period;
            if (p > 0)
                time += p; // 固定频率
            else
                time = now() - p; // 固定延迟
        }
        
        /**
         * 取消任务
         * 
         * @param mayInterruptIfRunning 是否中断正在执行的任务
         * @return 取消是否成功
         */
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            boolean cancelled = super.cancel(mayInterruptIfRunning);
            if (cancelled && removeOnCancel && heapIndex >= 0)
                remove(this);
            return cancelled;
        }
        
        /**
         * 执行任务的核心方法
         */
        @Override
        public void run() {
            boolean periodic = isPeriodic();
            if (!canRunInCurrentRunState(periodic))
                cancel(false);
            else if (!periodic)
                ScheduledFutureTask.super.run();
            else if (ScheduledFutureTask.super.runAndReset()) {
                setNextRunTime();
                reExecutePeriodic(outerTask);
            }
        }
    }
    
    /**
     * 用于生成任务序列号的原子长整数
     */
    private static final AtomicLong sequencer = new AtomicLong();
    
    // 用于保存延迟任务的延迟队列
    private static final AtomicLong sequencer = new AtomicLong();
    
    // 用于保存延迟任务的延迟队列
    private final DelayedWorkQueue workQueue;
    
    // 任务取消时是否从队列中移除
    private volatile boolean removeOnCancel = false;
    
    // 伪随机数生成器,用于线程工厂
    private static final AtomicLong sequencer = new AtomicLong();
    
    /**
     * 构造方法 - 指定核心线程数
     * 
     * @param corePoolSize 核心线程数
     */
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
        this.workQueue = (DelayedWorkQueue) super.getQueue();
    }
    
    /**
     * 构造方法 - 指定核心线程数和线程工厂
     * 
     * @param corePoolSize 核心线程数
     * @param threadFactory 线程工厂
     */
    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       ThreadFactory threadFactory) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue(), threadFactory);
        this.workQueue = (DelayedWorkQueue) super.getQueue();
    }
    
    /**
     * 构造方法 - 指定核心线程数和拒绝策略
     * 
     * @param corePoolSize 核心线程数
     * @param handler 拒绝策略
     */
    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       RejectedExecutionHandler handler) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue(), handler);
        this.workQueue = (DelayedWorkQueue) super.getQueue();
    }
    
    /**
     * 构造方法 - 指定核心线程数、线程工厂和拒绝策略
     * 
     * @param corePoolSize 核心线程数
     * @param threadFactory 线程工厂
     * @param handler 拒绝策略
     */
    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       ThreadFactory threadFactory,
                                       RejectedExecutionHandler handler) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue(), threadFactory, handler);
        this.workQueue = (DelayedWorkQueue) super.getQueue();
    }
    
    /**
     * 获取当前纳秒时间
     * 
     * @return 当前纳秒时间
     */
    final long nanoTime() {
        return System.nanoTime();
    }
    
    /**
     * 触发时间计算
     * 
     * @param delay 延迟时间
     * @param unit 时间单位
     * @return 触发时间
     */
    private long triggerTime(long delay, TimeUnit unit) {
        return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));
    }
    
    /**
     * 触发时间计算
     * 
     * @param delay 延迟时间(纳秒)
     * @return 触发时间
     */
    long triggerTime(long delay) {
        return now() + ((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay));
    }
    
    /**
     * 处理延迟时间溢出
     * 
     * @param delay 延迟时间
     * @return 处理后的延迟时间
     */
    private long overflowFree(long delay) {
        Delayed head = (Delayed) workQueue.peek();
        if (head != null) {
            long headDelay = head.getDelay(NANOSECONDS);
            if (headDelay < 0 && (delay - headDelay < 0))
                delay = Long.MAX_VALUE + headDelay;
        }
        return delay;
    }
    
    /**
     * 在给定延迟时间后执行Runnable任务
     */
    @Override
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay,
                                       TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture<?> t = decorateTask(command,
            new ScheduledFutureTask<Void>(command, null,
                                          triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }
    
    /**
     * 在给定延迟时间后执行Callable任务
     */
    @Override
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay,
                                           TimeUnit unit) {
        if (callable == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture<V> t = decorateTask(callable,
            new ScheduledFutureTask<V>(callable,
                                       triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }
    
    /**
     * 创建并执行固定频率的周期性任务
     */
    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        if (period <= 0)
            throw new IllegalArgumentException();
        ScheduledFutureTask<Void> sft =
            new ScheduledFutureTask<Void>(command,
                                          null,
                                          triggerTime(initialDelay, unit),
                                          unit.toNanos(period));
        RunnableScheduledFuture<Void> t = decorateTask(command, sft);
        sft.outerTask = t;
        delayedExecute(t);
        return t;
    }
    
    /**
     * 创建并执行固定延迟的周期性任务
     */
    @Override
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        if (delay <= 0)
            throw new IllegalArgumentException();
        ScheduledFutureTask<Void> sft =
            new ScheduledFutureTask<Void>(command,
                                          null,
                                          triggerTime(initialDelay, unit),
                                          unit.toNanos(-delay));
        RunnableScheduledFuture<Void> t = decorateTask(command, sft);
        sft.outerTask = t;
        delayedExecute(t);
        return t;
    }
    
    /**
     * 延迟执行任务
     */
    private void delayedExecute(RunnableScheduledFuture<?> task) {
        if (isShutdown())
            reject(task);
        else {
            super.getQueue().add(task);
            if (isShutdown() &&
                !canRunInCurrentRunState(task.isPeriodic()) &&
                remove(task))
                task.cancel(false);
            else
                ensurePrestart();
        }
    }
    
    /**
     * 判断在当前运行状态下是否可以执行任务
     */
    boolean canRunInCurrentRunState(boolean periodic) {
        return isRunningOrShutdown(periodic ?
                                   continueExistingPeriodicTasksAfterShutdown :
                                   executeExistingDelayedTasksAfterShutdown);
    }
    
    /**
     * 重新执行周期性任务
     */
    void reExecutePeriodic(RunnableScheduledFuture<?> task) {
        if (canRunInCurrentRunState(true)) {
            super.getQueue().add(task);
            if (!canRunInCurrentRunState(true) && remove(task))
                task.cancel(false);
            else
                ensurePrestart();
        }
    }
    
    /**
     * 确保预启动核心线程
     */
    private void ensurePrestart() {
        int wc = workerCountOf(ctl.get());
        if (wc < corePoolSize)
            addWorker(null, true);
        else if (wc == 0)
            addWorker(null, false);
    }
    
    /**
     * 装饰任务 - 可以被子类重写以自定义任务行为
     */
    protected <V> RunnableScheduledFuture<V> decorateTask(
            Runnable runnable, RunnableScheduledFuture<V> task) {
        return task;
    }
    
    /**
     * 装饰任务 - 可以被子类重写以自定义任务行为
     */
    protected <V> RunnableScheduledFuture<V> decorateTask(
            Callable<V> callable, RunnableScheduledFuture<V> task) {
        return task;
    }
    
    /**
     * 设置任务取消时是否从队列中移除
     */
    public void setRemoveOnCancelPolicy(boolean value) {
        removeOnCancel = value;
    }
    
    /**
     * 获取任务取消时是否从队列中移除的策略
     */
    public boolean getRemoveOnCancelPolicy() {
        return removeOnCancel;
    }
    
    /**
     * 关闭线程池
     */
    @Override
    public void shutdown() {
        super.shutdown();
    }
    
    /**
     * 立即关闭线程池
     */
    @Override
    public List<Runnable> shutdownNow() {
        return super.shutdownNow();
    }
    
    /**
     * 获取队列
     */
    @Override
    public BlockingQueue<Runnable> getQueue() {
        return super.getQueue();
    }
}

4. DelayedWorkQueue延迟工作队列源码

/*
 * DelayedWorkQueue是ScheduledThreadPoolExecutor的内部类
 * 实现了基于堆的延迟队列,用于存储和管理延迟任务
 */
static class DelayedWorkQueue extends AbstractQueue<Runnable>
    implements BlockingQueue<Runnable> {
    
    /*
     * 队列容量 - 初始容量为16,最大容量为Integer.MAX_VALUE
     */
    private static final int INITIAL_CAPACITY = 16;
    private RunnableScheduledFuture<?>[] queue =
        new RunnableScheduledFuture<?>[INITIAL_CAPACITY];
    private final ReentrantLock lock = new ReentrantLock();
    private int size = 0;
    
    // 等待队列头部任务的线程
    private Thread leader = null;
    
    // 条件变量,用于通知等待线程
    private final Condition available = lock.newCondition();
    
    /**
     * 设置堆中元素的索引
     */
    private void setIndex(RunnableScheduledFuture<?> f, int idx) {
        if (f instanceof ScheduledThreadPoolExecutor.ScheduledFutureTask)
            ((ScheduledThreadPoolExecutor.ScheduledFutureTask)f).heapIndex = idx;
    }
    
    /**
     * 堆向上调整 - 维护最小堆性质
     */
    private void siftUp(int k, RunnableScheduledFuture<?> key) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            RunnableScheduledFuture<?> e = queue[parent];
            if (key.compareTo(e) >= 0)
                break;
            queue[k] = e;
            setIndex(e, k);
            k = parent;
        }
        queue[k] = key;
        setIndex(key, k);
    }
    
    /**
     * 堆向下调整 - 维护最小堆性质
     */
    private void siftDown(int k, RunnableScheduledFuture<?> key) {
        int half = size >>> 1;
        while (k < half) {
            int child = (k << 1) + 1;
            RunnableScheduledFuture<?> c = queue[child];
            int right = child + 1;
            if (right < size && c.compareTo(queue[right]) > 0)
                c = queue[child = right];
            if (key.compareTo(c) <= 0)
                break;
            queue[k] = c;
            setIndex(c, k);
            k = child;
        }
        queue[k] = key;
        setIndex(key, k);
    }
    
    /**
     * 重新调整堆
     */
    private void heapify() {
        for (int i = size >>> 1; i >= 0; i--)
            siftDown(i, queue[i]);
    }
    
    /**
     * 扩容队列
     */
    private void grow() {
        int oldCapacity = queue.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1); // 扩容50%
        if (newCapacity < 0) // 溢出检查
            newCapacity = Integer.MAX_VALUE;
        queue = Arrays.copyOf(queue, newCapacity);
    }
    
    /**
     * 查找元素索引
     */
    private int indexOf(Object x) {
        if (x != null) {
            if (x instanceof ScheduledThreadPoolExecutor.ScheduledFutureTask) {
                int i = ((ScheduledThreadPoolExecutor.ScheduledFutureTask)x).heapIndex;
                // 检查索引是否有效
                if (i >= 0 && i < size && queue[i] == x)
                    return i;
            } else {
                for (int i = 0; i < size; i++)
                    if (x.equals(queue[i]))
                        return i;
            }
        }
        return -1;
    }
    
    /**
     * 添加元素
     */
    @Override
    public boolean offer(Runnable x) {
        if (x == null)
            throw new NullPointerException();
        RunnableScheduledFuture<?> e = (RunnableScheduledFuture<?>)x;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int i = size;
            if (i >= queue.length)
                grow();
            size = i + 1;
            if (i == 0) {
                queue[0] = e;
                setIndex(e, 0);
            } else {
                siftUp(i, e);
            }
            if (queue[0] == e) {
                leader = null;
                available.signal();
            }
        } finally {
            lock.unlock();
        }
        return true;
    }
    
    /**
     * 插入元素,阻塞直到有空间
     */
    @Override
    public void put(Runnable e) {
        offer(e);
    }
    
    /**
     * 插入元素,带超时控制
     */
    @Override
    public boolean offer(Runnable e, long timeout, TimeUnit unit) {
        return offer(e);
    }
    
    /**
     * 获取并移除队列头部元素
     */
    private RunnableScheduledFuture<?> finishPoll(RunnableScheduledFuture<?> f) {
        int s = --size;
        RunnableScheduledFuture<?> x = queue[s];
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        setIndex(f, -1);
        return f;
    }
    
    /**
     * 获取并移除队列头部元素
     */
    @Override
    public RunnableScheduledFuture<?> poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            RunnableScheduledFuture<?> first = queue[0];
            if (first == null || first.getDelay(NANOSECONDS) > 0)
                return null;
            else
                return finishPoll(first);
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 获取并移除队列头部元素,阻塞直到有元素或超时
     */
    @Override
    public RunnableScheduledFuture<?> poll(long timeout, TimeUnit unit)
        throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            for (;;) {
                RunnableScheduledFuture<?> first = queue[0];
                if (first == null) {
                    if (nanos <= 0)
                        return null;
                    else
                        nanos = available.awaitNanos(nanos);
                } else {
                    long delay = first.getDelay(NANOSECONDS);
                    if (delay <= 0)
                        return finishPoll(first);
                    if (nanos <= 0)
                        return null;
                    first = null; // 不再引用队列头部
                    if (nanos < delay || leader != null)
                        nanos = available.awaitNanos(nanos);
                    else {
                        Thread thisThread = Thread.currentThread();
                        leader = thisThread;
                        try {
                            long timeLeft = available.awaitNanos(delay);
                            nanos -= delay - timeLeft;
                        } finally {
                            if (leader == thisThread)
                                leader = null;
                        }
                    }
                }
            }
        } finally {
            if (leader == null && queue[0] != null)
                available.signal();
            lock.unlock();
        }
    }
    
    /**
     * 获取并移除队列头部元素,阻塞直到有元素
     */
    @Override
    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; // 不再引用队列头部
                    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();
        }
    }
    
    /**
     * 获取但不移除队列头部元素
     */
    @Override
    public RunnableScheduledFuture<?> peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return queue[0];
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 移除指定元素
     */
    @Override
    public boolean remove(Object x) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int i = indexOf(x);
            if (i < 0)
                return false;
            
            setIndex(queue[i], -1);
            int s = --size;
            RunnableScheduledFuture<?> replacement = queue[s];
            queue[s] = null;
            if (s != i) {
                siftDown(i, replacement);
                if (queue[i] == replacement)
                    siftUp(i, replacement);
            }
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 获取队列大小
     */
    @Override
    public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return size;
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 获取剩余容量
     */
    @Override
    public int remainingCapacity() {
        return Integer.MAX_VALUE;
    }
    
    /**
     * 转换为数组
     */
    @Override
    public Object[] toArray() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return Arrays.copyOf(queue, size, Object[].class);
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 转换为数组
     */
    @Override
    public <T> T[] toArray(T[] a) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (a.length < size)
                return (T[]) Arrays.copyOf(queue, size, a.getClass());
            System.arraycopy(queue, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 清空队列
     */
    @Override
    public void clear() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            for (int i = 0; i < size; i++) {
                RunnableScheduledFuture<?> x = queue[i];
                if (x != null) {
                    queue[i] = null;
                    setIndex(x, -1);
                }
            }
            size = 0;
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * drainTo方法实现
     */
    @Override
    public int drainTo(Collection<? super Runnable> c) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int n = 0;
            for (int i = 0; i < size; i++) {
                RunnableScheduledFuture<?> first = queue[0];
                if (first != null && first.getDelay(NANOSECONDS) <= 0) {
                    c.add(first);
                    finishPoll(first);
                    ++n;
                } else
                    break;
            }
            return n;
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * drainTo方法实现,带最大元素数量限制
     */
    @Override
    public int drainTo(Collection<? super Runnable> c, int maxElements) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        if (maxElements <= 0)
            return 0;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int n = 0;
            while (n < maxElements) {
                RunnableScheduledFuture<?> first = queue[0];
                if (first != null && first.getDelay(NANOSECONDS) <= 0) {
                    c.add(first);
                    finishPoll(first);
                    ++n;
                } else
                    break;
            }
            return n;
        } finally {
            lock.unlock();
        }
    }
}

5. Executors工具类中的定时任务方法

public class Executors {
    
    /**
     * 创建单线程的ScheduledExecutorService
     * 
     * @return ScheduledExecutorService实例
     */
    public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1));
    }
    
    /**
     * 创建单线程的ScheduledExecutorService,指定线程工厂
     * 
     * @param threadFactory 线程工厂
     * @return ScheduledExecutorService实例
     */
    public static ScheduledExecutorService newSingleThreadScheduledExecutor(
            ThreadFactory threadFactory) {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1, threadFactory));
    }
    
    /**
     * 创建指定核心线程数的ScheduledExecutorService
     * 
     * @param corePoolSize 核心线程数
     * @return ScheduledExecutorService实例
     */
    public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    
    /**
     * 创建指定核心线程数的ScheduledExecutorService,指定线程工厂
     * 
     * @param corePoolSize 核心线程数
     * @param threadFactory 线程工厂
     * @return ScheduledExecutorService实例
     */
    public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize, ThreadFactory threadFactory) {
        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
    }
}

6. 核心设计要点总结

6.1 延迟任务管理

  • 使用DelayedWorkQueue作为任务队列,基于最小堆实现
  • 通过getDelay()方法判断任务是否到期
  • 支持精确的时间控制和任务排序

6.2 周期性任务处理

  • 固定频率(Fixed Rate): scheduleAtFixedRate
    • 任务按固定时间间隔执行
    • 不管前一个任务是否完成
  • 固定延迟(Fixed Delay): scheduleWithFixedDelay
    • 每个任务完成后等待固定时间再执行下一次
    • 确保任务之间有足够间隔

6.3 任务生命周期管理

  • 通过sequenceNumber保证相同延迟时间的任务按FIFO顺序执行
  • 支持任务取消和从队列中移除
  • 提供灵活的关闭策略

6.4 线程池管理

  • 继承ThreadPoolExecutor,复用线程池管理机制
  • 核心线程数可配置
  • 支持优雅关闭和强制关闭

6.5 性能优化

  • 使用堆结构实现O(log n)的插入和删除操作
  • 通过leader-follower模式优化线程等待
  • 支持任务取消时的快速移除

这些设计使得ScheduledThreadPoolExecutor成为Java中强大的定时任务调度工具,广泛应用于需要定时执行或周期性执行任务的场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值