Java并发学习笔记 (十) ScheduledThreadPoolExecutor

Java并发学习笔记 (十) ScheduledThreadPoolExecutor

目录

Java并发学习笔记 (十) ScheduledThreadPoolExecutor

一. 简介

二.  FutureTask

2.1  Callable接口

2.2  Future接口

2.3  FutureTask

2.4  FutureTask源码分析

2.4.1  成员变量

2.4.2  成员方法:  run()

2.4.3 成员方法:  get()

2.4.4  成员方法:  cancel (boolean mayInterruptIfRunning)

三.  构造方法

四.  ScheduledFutureTask

五.  DelayedWorkQueue

六.   ScheduledThreadPoolExecutor的执行

七. 总结

Refference


一. 简介

ScheduledThreadPoolExecutor是一个使用线程池执行定时任务的类相较于Java中提供的另一个执行定时任务的类Timer,其主要有如下两个优点:

  • 使用多线程执行任务,不用担心任务执行时间过长而导致任务相互阻塞的情况,Timer是单线程执行的,因而会出现这个问题;
  • 不用担心任务执行过程中,如果线程失活,其会新建线程执行任务,Timer类的单线程挂掉之后是不会重新创建线程执行后续任务的。

主要原因是Timer有三个大的缺陷:

1、不能捕获任务执行中的异常,如果出现一次异常整个定时任务执行将停止执行;

2、Timer是基于Date时钟的,在分布式环境下由于机器的时钟不一致会导致一些致命的问题;

3、Timer只会创建一个线程,存在任务丢失问题(任务执行时间超过一个周期时)。

而ScheduledThreadPoolExecutor巧好能解决上述3个问题:

1、ScheduledThreadPoolExecutor可以捕获异常,当然如果不捕获异常 该线程会中止;

2、ScheduledThreadPoolExecutor是基于相对时间;

3、ScheduledThreadPoolExecutor本质上是线程池,并可以保证每次任务都会执行。

ScheduledThreadPoolExecutor类的UML图:

  • 从UML图可以看出,ScheduledThreadPoolExecutor继承了ThreadPoolExecutor,也就是说ScheduledThreadPoolExecutor拥有execute()和submit()提交异步任务的基础功能,但是,ScheduledThreadPoolExecutor类实现了ScheduledExecutorService,该接口定义了ScheduledThreadPoolExecutor能够延时执行任务和周期执行任务的功能;
  • ScheduledThreadPoolExecutor也两个重要的内部类:DelayedWorkQueueScheduledFutureTask。可以看出DelayedWorkQueue实现了BlockingQueue接口,也就是一个阻塞队列,ScheduledFutureTask则是继承了FutureTask类,也表示该类用于返回异步任务的结果。

ScheduledThreadPoolExecutor实现“延迟任务和周期性任务”的核心方法,一共4个方法:

//达到给定的延时时间后,执行任务。这里传入的是实现Runnable接口的任务,
//因此通过ScheduledFuture.get()获取结果为null
public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);
//达到给定的延时时间后,执行任务。这里传入的是实现Callable接口的任务,
//因此,返回的是任务的最终计算结果
 public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit);

//是以上一个任务开始的时间计时,period时间过去后,
//检测上一个任务是否执行完毕,如果上一个任务执行完毕,
//则当前任务立即执行,如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);
//当达到延时时间initialDelay后,任务开始执行。上一个任务执行结束后到下一次
//任务执行,中间延时时间间隔为delay。以这种方式,周期性执行任务。
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);

二.  FutureTask

2.1  Callable接口

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Callable接口很简单,是一个泛型接口,就是定义了一个call()方法,与Runnable的 run() 方法相比,这个有返回值,泛型V就是要返回的结果类型,可以返回子任务的执行结果。

那么怎么使用Callable呢?一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本:

<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);

2.2  Future接口

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。接口的定义如下:

public interface Future<V> {

    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();

    V get() throws InterruptedException, ExecutionException;

    V get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException;
}
  1. cancel(boolean mayInterruptIfRunning):取消子任务的执行,如果这个子任务已经执行结束,或者已经被取消,或者不能被取消,这个方法就会执行失败并返回 false;如果子任务还没有开始执行,那么子任务会被取消,不会再被执行;如果子任务已经开始执行了,但是还没有执行结束,根据 mayInterruptIfRunning 的值,如果 mayInterruptIfRunning = true,那么会中断执行任务的线程,然后返回true,如果参数为false,会返回true,不会中断执行任务的线程。这个方法在FutureTask的实现中有很多值得关注的地方,后面再细说。

    需要注意,这个方法执行结束,返回结果之后,再调用 isDone() 会返回true。

  2. isCancelled():判断任务是否被取消,如果任务执行结束(正常执行结束和发生异常结束,都算执行结束)前被取消,也就是调用了cancel()方法,并且cancel()返回true,则该方法返回true,否则返回false.

  3. isDone(): 判断任务是否执行结束,正常执行结束,或者发生异常结束,或者被取消,都属于结束,该方法都会返回true.

  4. V get(): 获取结果,如果这个计算任务还没有执行结束,该调用线程会进入阻塞状态。如果计算任务已经被取消,调用get()会抛出CancellationException,如果计算过程中抛出异常,该方法会抛出ExecutionException,如果当前线程在阻塞等待的时候被中断了,该方法会抛出InterruptedException

  5. V get(long timeout, TimeUnit unit):带超时限制的get(),等待超时之后,该方法会抛出TimeoutException

也就是说Future提供了三种功能:

  1)判断任务是否完成;

  2)能够中断任务;

  3)能够获取任务执行结果。

  因为Future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了下面的FutureTask。

2.3  FutureTask

FutureTask可以像Runnable一下,封装异步任务,然后提交Thread或线程池执行,然后获取任务执行结果。

因为FutureTask类实现了RunnableFuture接口,而RunnableFuture继承了Runnable接口和Future接口

FutureTask提供了2个构造器:

public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}

事实上,FutureTask是Future接口的一个唯一实现类。

使用Demo:

1.  FutureTask + Thread

//step1:封装一个计算任务,实现Callable接口   
class Task implements Callable<Boolean> {

    @Override
    public Boolean call() throws Exception {
        try {
            for (int i = 0; i < 10; i++) {
                Log.d(TAG, "task......." + Thread.currentThread().getName() + "...i = " + i);
                //模拟耗时操作
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            Log.e(TAG, " is interrupted when calculating, will stop...");
            return false; // 注意这里如果不return的话,线程还会继续执行,所以任务超时后在这里处理结果然后返回
        }
        return true;
    }
}

//step2:创建计算任务,作为参数,传入FutureTask
Task task = new Task();
FutureTask futureTask = new FutureTask(task);
//step3:将FutureTask提交给Thread执行
Thread thread1 = new Thread(futureTask);
thread1.setName("task thread 1");
thread1.start();

//step4:获取执行结果,由于get()方法可能会阻塞当前调用线程,如果子任务执行时间不确定,最好在子线程中获取执行结果
try {
    // boolean result = (boolean) futureTask.get();
    boolean result = (boolean) futureTask.get(5, TimeUnit.SECONDS);
    Log.d(TAG, "result:" + result);
} catch (InterruptedException e) {
    Log.e(TAG, "守护线程阻塞被打断...");
    e.printStackTrace();
} catch (ExecutionException e) {
    Log.e(TAG, "执行任务时出错...");
    e.printStackTrace();
} catch (TimeoutException e) {
    Log.e(TAG, "执行超时...");
    futureTask.cancel(true);
    e.printStackTrace();
} catch (CancellationException e) {
    //如果线程已经cancel了,再执行get操作会抛出这个异常
    Log.e(TAG, "future已经cancel了...");
    e.printStackTrace();
}

2.  Future + ExecutorService

//step1 ......
//step2:创建计算任务
Task task = new Task();
//step3:创建线程池,将Callable类型的task提交给线程池执行,通过Future获取子任务的执行结果
ExecutorService executorService = Executors.newCachedThreadPool();
final Future<Boolean> future = executorService.submit(task);
//step4:通过future获取执行结果
boolean result = (boolean) future.get();

3.  FutureTask + ExecutorService

//step1 ......
//step2 ......
//step3:将FutureTask提交给线程池执行
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(futureTask);
//step4 ......

2.4  FutureTask源码分析

2.4.1  成员变量

  1. private volatile int state  :state 用来标识当前任务的运行状态。FutureTask的所有方法都是围绕这个状态进行的,需要注意,这个值用 volatile 来标记,如果有多个子线程在执行FutureTask,那么它们看到的都会是同一个state,有如下几个值:
    private static final int NEW          = 0; //任务新建和执行中
    private static final int COMPLETING   = 1; //任务将要执行完毕
    private static final int NORMAL       = 2; //任务正常执行结束
    private static final int EXCEPTIONAL  = 3; //任务异常
    private static final int CANCELLED    = 4; //任务取消
    private static final int INTERRUPTING = 5; //任务线程即将被中断
    private static final int INTERRUPTED  = 6; //任务线程已中断
  2. private Callable<V> callable: 一个Callable类型的变量,封装了计算任务,可获取计算结果。从上面的用法中可以看到,FutureTask的构造函数中,我们传入的就是实现了Callable的接口的计算任务。

  3. private Object outcome:  Object类型的变量outcome,用来保存计算任务的返回结果,或者执行过程中抛出的异常。
  4. private volatile Thread runner : 指向当前在运行Callable任务的线程,runner  在FutureTask中的赋值变化很值得关注,后面源码会详细介绍这个。
  5. private volatile WaitNode waiters : WaitNode是FutureTask的内部类,表示一个阻塞队列,如果任务还没有执行结束,那么调用get()获取结果的线程会阻塞,在这个阻塞队列中排队等待。
  6. long stateOffset: state字段的内存偏移量
  7. long runnerOffset:runner字段的内存偏移量
  8. long waitersOffset:waiters字段的内存偏移量 

NEW:表示这是一个新的任务,或者还没有执行完的任务,是初始状态。
COMPLETING:表示任务执行结束(正常执行结束,或者发生异常结束),但是还没有将结果保存到outcome中。是一个中间状态。
NORMAL:表示任务正常执行结束,并且已经把执行结果保存到outcome字段中。是一个最终状态。
EXCEPTIONAL:表示任务发生异常结束,异常信息已经保存到outcome中,这是一个最终状态。
CANCELLED:任务在新建之后,执行结束之前被取消了,但是不要求中断正在执行的线程,也就是调用了cancel(false),任务就是CANCELLED状态,这时任务状态变化是NEW -> CANCELLED
INTERRUPTING:任务在新建之后,执行结束之前被取消了,并要求中断线程的执行,也就是调用了cancel(true),这时任务状态就是INTERRUPTING。这是一个中间状态。
INTERRUPTED:调用cancel(true)取消异步任务,会调用interrupt()中断线程的执行,然后状态会从INTERRUPTING变到INTERRUPTED

后三个字段是配合Unsafe类做CAS操作使用的。

状态变化有如下4种情况:
NEW -> COMPLETING -> NORMAL --------------------------------------- 正常执行结束的流程
NEW -> COMPLETING -> EXCEPTIONAL ---------------------执行过程中出现异常的流程
NEW -> CANCELLED -------------------------------------------被取消,即调用了cancel(false)
NEW -> INTERRUPTING -> INTERRUPTED -------------被中断,即调用了cancel(true)

2.4.2  成员方法:  run()

public void run() {
    //1.判断状态是否是NEW,不是NEW,说明任务已经被其他线程执行,甚至执行结束,或者被取消了,直接返回
    //2.调用CAS方法,判断RUNNER为null的话,就将当前线程保存到RUNNER中,设置RUNNER失败,就直接返回
    if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                //3.执行Callable任务,结果保存到result中
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                //3.1 如果执行任务过程中发生异常,将调用setException()设置异常
                result = null;
                ran = false;
                setException(ex);
            }
            //3.2 任务正常执行结束调用set(result)保存结果
            if (ran)
                set(result);
        }
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        //4. 任务执行结束,runner设置为null,表示当前没有线程在执行这个任务了
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        //5. 读取状态,判断是否在执行的过程中,被中断了,如果被中断,处理中断
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}

2.4.3 成员方法:  get()

一般情况下,执行任务的线程和获取结果的线程不会是同一个,当我们在主线程或者其他线程中,获取计算任务的结果时,就会调用get方法,如果这时计算任务还没有执行完成,调用get()的线程就会阻塞等待。

public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    return report(s);
}

public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

get的源码很简洁,首先校验参数,然后根据state状态判断是否超时,如果超时则异常,不超时则调用report(s)去获取最终结果。

当 s<= COMPLETING时,表明任务仍然在执行且没有被取消。如果它为true,那么走到awaitDone方法。

awaitDone() 是futureTask实现阻塞的关键方法。

/**
 1. 等待任务执行完毕,如果任务取消或者超时则停止
 2. @param timed 为true表示设置超时时间
 3. @param nanos 超时时间
 4. @return 任务完成时的状态
 5. @throws InterruptedException
 */
private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
    long startTime = 0L;    // Special value 0L means not yet parked
    WaitNode q = null;
    boolean queued = false;
    for (;;) {
        //1. 读取状态
        //1.1 如果s > COMPLETING,表示任务已经执行结束,或者发生异常结束了,就不会阻塞,直接返回
        int s = state;
        if (s > COMPLETING) {
            if (q != null)
                q.thread = null;
            return s;
        }
        //1.2 如果s == COMPLETING,表示任务结束(正常/异常),但是结果还没有保存到outcome字段,当前线程让出执行权,给其他线程先执行
        else if (s == COMPLETING)
            // We may have already promised (via isDone) that we are done
            // so never return empty-handed or throw InterruptedException
            Thread.yield();
        //2. 如果调用get()的线程被中断了,就从等待的线程栈中移除这个等待节点,然后抛出中断异常
        else if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }
        //3. 如果等待节点q=null,就创建一个等待节点
        else if (q == null) {
            if (timed && nanos <= 0L)
                return s;
            q = new WaitNode();
        }
        //4. 如果这个等待节点还没有加入等待队列,就加入队列头
        else if (!queued)
            queued = U.compareAndSwapObject(this, WAITERS,
                    q.next = waiters, q);
        //5. 如果设置了超时等待时间
        else if (timed) {
            //5.1 设置startTime,用于计算超时时间,如果超时时间到了,就等待队列中移除当前节点
            final long parkNanos;
            if (startTime == 0L) { // first time
                startTime = System.nanoTime();
                if (startTime == 0L)
                    startTime = 1L;
                parkNanos = nanos;
            } else {
                long elapsed = System.nanoTime() - startTime;
                if (elapsed >= nanos) {
                    removeWaiter(q);
                    return state;
                }
                parkNanos = nanos - elapsed;
            }
            // nanoTime may be slow; recheck before parking
            //5.2 如果超时时间还没有到,而且任务还没有结束,就阻塞特定时间
            if (state < COMPLETING)
                LockSupport.parkNanos(this, parkNanos);
        }
        //6. 阻塞,等待唤醒
        else
            LockSupport.park(this);
    }
}

2.4.4  成员方法:  cancel (boolean mayInterruptIfRunning)

通常调用cancel ()的线程和执行子任务的线程不会是同一个。当FutureTask的 cancel (boolean mayInterruptIfRunning)方法被调用时,如果子任务还没有执行,那么这个任务就不会执行了,如果子任务已经执行,且 mayInterruptIfRunning = true,那么执行子任务的线程会被中断(注意:这里说的是线程被中断,不是任务被取消),下面看一下这个方法的实现:

public boolean cancel(boolean mayInterruptIfRunning) {
    //1.判断state是否为NEW,如果不是NEW,说明任务已经结束或者被取消了,该方法会执行返回false
    //state=NEW时,判断mayInterruptIfRunning,如果mayInterruptIfRunning=true,说明要中断任务的执行,NEW->INTERRUPTING
    //如果mayInterruptIfRunning=false,不需要中断,状态改为CANCELLED
    if (!(state == NEW &&
            U.compareAndSwapInt(this, STATE, NEW,
                    mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
        return false;
    try {    // in case call to interrupt throws exception
        if (mayInterruptIfRunning) {
            try {
                //2.读取当前正在执行子任务的线程runner,调用t.interrupt(),中断线程执行
                Thread t = runner;
                if (t != null)
                    t.interrupt();
            } finally { // final state
                //3.修改状态为INTERRUPTED
                U.putOrderedInt(this, STATE, INTERRUPTED);
            }
        }
    } finally {
        finishCompletion();
    }
    return true;
}

三.  构造方法

ScheduledThreadPoolExecutor有如下几个构造方法:

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

public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue(), threadFactory);
};
public ScheduledThreadPoolExecutor(int corePoolSize,
                                   RejectedExecutionHandler handler) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue(), handler);
};

public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory,
                                   RejectedExecutionHandler handler) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue(), threadFactory, handler);
}

可以看出由于ScheduledThreadPoolExecutor继承了ThreadPoolExecutor,它的构造方法实际上是调用了ThreadPoolExecutor,对ThreadPoolExecutor的介绍可以可以看这篇文章,理解ThreadPoolExecutor构造方法的几个参数的意义后,理解这就很容易了。可以看出,ScheduledThreadPoolExecutor的核心线程池的线程个数为指定的corePoolSize,当核心线程池的线程个数达到corePoolSize后,就会将任务提交给有界阻塞队列DelayedWorkQueue,对DelayedWorkQueue在下面进行详细介绍,线程池允许最大的线程个数为Integer.MAX_VALUE,也就是说理论上这是一个大小无界的线程池。

ScheduledThreadPoolExecutor也两个重要的内部类:DelayedWorkQueue和ScheduledFutureTask。可以看出DelayedWorkQueue实现了BlockingQueue接口,也就是一个阻塞队列,ScheduledFutureTask则是继承了FutureTask类,也表示该类用于返回异步任务的结果。这两个关键类,下面会具体详细来看。

四.  ScheduledFutureTask

关系有点复杂,但我们只需要知道ScheduledFutureTask从根本上实现了三个接口:Future、Runnable、Delayed,

ScheduledFutureTask相对于FutureTask而言,多实现了一个Delayed接口,这个是关键。因为ScheduledThreadPoolExecutor 的任务队列是DelayedWorkQueue,该队列要求放入的对象必须是实现了Delayed接口的RunnableScheduledFuture类型,而ScheduledFutureTask刚好实现了RunnableScheduledFuture。放入队列的入口就是delayedExecute方法。

private void delayedExecute(RunnableScheduledFuture<?> task) {  
        if (isShutdown())//线程池已关闭,执行拒绝策略  
            reject(task);  
        else {  
            super.getQueue().add(task);//调用任务队列的add方法加入队列  
            if (isShutdown() &&  
                !canRunInCurrentRunState(task.isPeriodic()) &&  
                remove(task))  
                task.cancel(false); //取消任务  
            else  
                ensurePrestart();//是否需要创建新线程  
        }  
    }  

这里主要的操作就是super.getQueue().add(task),调用“任务队列”的add方法把任务放入队列。这个队列在构造方法中,已经可以看出来了,是DelayedWorkQueue。如何实现延迟任务,核心操作都在DelayedWorkQueue中实现。

五.  DelayedWorkQueue

DelayedWorkQueue主要维护了一个由二叉堆算法实现的数组。简单的理解就是在调用add方法插入队列时,采用二叉堆算法保证第一个元素是最小值。在这里其实就是Delay时间最短的值。

在执行定时任务的时候,每个任务的执行时间都不同,所以DelayedWorkQueue的工作就是按照执行时间的升序来排列,执行时间距离当前时间越近的任务在队列的前面。

定时任务执行时需要取出最近要执行的任务,所以任务在队列中每次出队时一定要是当前队列中执行时间最靠前的,所以自然要使用优先级队列。

DelayedWorkQueue是一个优先级队列,它可以保证每次出队的任务都是当前队列中执行时间最靠前的,由于它是基于堆结构的队列,堆结构在执行插入和删除操作时的最坏时间复杂度是 O(logN)。

总结:DelayedWorkQueue是基于堆的数据结构,按照时间顺序将每个任务进行排序,将待执行时间越近的任务放在在队列的队头位置,以便于最先进行执行

六.   ScheduledThreadPoolExecutor的执行

现在我们对ScheduledThreadPoolExecutor的两个内部类ScheduledFutueTask和DelayedWorkQueue进行了了解,实际上这也是线程池工作流程中最重要的两个关键因素:任务以及阻塞队列

public ScheduledFuture<?> schedule(Runnable command,
                                   long delay,
                                   TimeUnit unit) {
    if (command == null || unit == null)
        throw new NullPointerException();
	//将提交的任务转换成ScheduledFutureTask
    RunnableScheduledFuture<?> t = decorateTask(command,
        new ScheduledFutureTask<Void>(command, null,
                                      triggerTime(delay, unit)));
    //延时执行任务ScheduledFutureTask
	delayedExecute(t);
    return t;
}

方法很容易理解,为了满足ScheduledThreadPoolExecutor能够延时执行任务和能周期执行任务的特性,会先将实现Runnable接口的类转换成ScheduledFutureTask。然后会调用delayedExecute方法进行执行任务,这个方法也是关键方法,来看下源码:

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
			//保证至少有一个线程启动,即使corePoolSize=0
            ensurePrestart();
    }
}
void ensurePrestart() {
    int wc = workerCountOf(ctl.get());
    if (wc < corePoolSize)
        addWorker(null, true);
    else if (wc == 0)
        addWorker(null, false);
}

可以看出该方法逻辑很简单,关键在于它所调用的addWorker方法,该方法主要功能:新建Worker类,当执行任务时,就会调用被Worker所重写的run方法,进而会继续执行runWorker方法。在runWorker方法中会调用getTask方法从阻塞队列中不断的去获取任务进行执行,直到从阻塞队列中获取的任务为null的话,线程结束终止。addWorker方法是ThreadPoolExecutor类中的方法。

七. 总结

ScheduleThreadPoolExecutor本质上还是线程池,只是使用了DelayedWorkQueue作为任务队列。对应周期性任务而已,只是每次执行完成后,重新计算下一次执行时间,然后再重新放入队列而已。如果出现异常,没有捕获的话,就无法再次放入队列,周期性任务也就无法继续执行了。

  1. ScheduledThreadPoolExecutor继承了ThreadPoolExecutor类,因此,整体上功能一致,线程池主要负责创建线程(Worker类),线程从阻塞队列中不断获取新的异步任务,直到阻塞队列中已经没有了异步任务为止。但是相较于ThreadPoolExecutor来说,ScheduledThreadPoolExecutor具有延时执行任务和可周期性执行任务的特性,ScheduledThreadPoolExecutor重新设计了任务类ScheduleFutureTask,ScheduleFutureTask重写了run方法使其具有可延时执行和可周期性执行任务的特性。另外,阻塞队列DelayedWorkQueue是可根据优先级排序的队列,采用了堆的底层数据结构,使得与当前时间相比,待执行时间越靠近的任务放置队头,以便线程能够获取到任务进行执行;

  2. 线程池无论是ThreadPoolExecutor还是ScheduledThreadPoolExecutor,在设计时的三个关键要素是:任务,执行者以及任务结果。它们的设计思想也是完全将这三个关键要素进行了解耦。

    执行者

    任务的执行机制,完全交由Worker类,也就是进一步了封装了Thread。向线程池提交任务,无论为ThreadPoolExecutor的execute方法和submit方法,还是ScheduledThreadPoolExecutor的schedule方法,都是先将任务移入到阻塞队列中,然后通过addWork方法新建了Work类,并通过runWorker方法启动线程,并不断的从阻塞对列中获取异步任务执行交给Worker执行,直至阻塞队列中无法取到任务为止。

    任务

    在ThreadPoolExecutor和ScheduledThreadPoolExecutor中任务是指实现了Runnable接口和Callable接口的实现类。ThreadPoolExecutor中会将任务转换成FutureTask类,而在ScheduledThreadPoolExecutor中为了实现可延时执行任务和周期性执行任务的特性,任务会被转换成ScheduledFutureTask类,该类继承了FutureTask,并重写了run方法。

    任务结果

    在ThreadPoolExecutor中提交任务后,获取任务结果可以通过Future接口的类,在ThreadPoolExecutor中实际上为FutureTask类,而在ScheduledThreadPoolExecutor中则是ScheduledFutureTask

Refference

Java并发编程:Callable、Future和FutureTask

可取消的异步任务——FutureTask用法及解析

线程池之ScheduledThreadPoolExecutor

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值