Executor框架

一、Executor框架介绍

Executor框架是JDK1.5之后出现的,位于juc包中,是并发程序设计的工具之一。1.5之前Java的线程既是工作单元,也是执行机制。从JDK5开始,把工作单元和执行机制分离开来。工作单元包括Runnable和Callable,而执行机制由Executor框架提供。

Executor框架主要由4部分组成:

  • 任务的定义,包括被执行任务需要实现的接口:Runnable接口或者Callable接口。
  • 任务的提交,继承自Executor的ExecutorService接口,扩充了任务提交的方法submit
  • 任务的执行,任务执行机制的核心接口Executor,定义了execute方法
  • 任务的结果,异步计算的结果。包括Future,ScheduledFuture接口以及主要实现FutureTask,ScheduledFutureTask

主要实现,Executor框架有两个关键类实现了ExecutorService接口(ThreadPoolExecutor和ScheduledThreadPoolExecutor)

二、Executor框架的类结构图:

在这里插入图片描述

三、Executor框架的成员

  1. Executor接口
    Executor接口是整个框架的总接口,正如上面所述,它描述了框架的主要实现思想:任务内容与执行的解耦。其源码很短,我们可以看看:
package java.util.concurrent;
public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     * 
     * 在将来某一时刻执行给定的指令,该指令可能会在一个新的线程、或一个线程池中的线程、
     * 或在正调用的线程中执行,这取决于Executor接口的实现
     * 
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}
  1. ExecutorService接口
    ExecutorService接口继承了Executor接口,Executor接口仅仅描述了思想,定义了一个执行器,ExecutorService接口在其基础上进一步丰富了框架的接口,为框架定义了更多内容,包括:任务的提交,执行器的终止关闭等。
  • 任务的停止
/**
 * 终止新任务的接收,已接收的任务却需要继续执行。这是保证已提交任务全部执行的终止方法
 */
void shutdown();
/**
 * 强制终止方法,它会试图停止正在执行的线程任务(并不确保一定能停止,因为其实现会使用
 * Thread.interrupt()方法来进行线程任务中断执行,但是如果任务线程不会响应该中断,则不会被终止)
 * 并且不再执行处于等待状态的其他任务,将这些从未执行过的任务以列表的方式返回
 */
List<Runnable> shutdownNow();
  • 任务的提交
 /**
  * 任务执行成功后返回一个表示该任务的Future,通过其get方法可获取到在Callable任务中指定的返回内容
  */
 <T> Future<T> submit(Callable<T> task);
 /**
  * 第二个参数result为预设的返回值,任务执行成功通过Future返回值的get方法可获取到该预设值
  */
 <T> Future<T> submit(Runnable task, T result);
  /**
   * 任务执行成功会返回一个表示该任务的Future,通过get方法只能得到null,即无实际意义的返回值
   */
 Future<?> submit(Runnable task);

关于Callable与Future后面会简单介绍。

  • invokeAny 提交多个任务并全部执行,返回第一个执行成功的任务,若不存在(前面所有任务都执行异常,不成功),返回最后一个任务的执行异常(两种情况下,任务列表中其他未完成的任务皆取消执行)
<T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
  • invokeAll 提交多个任务并全部执行,当列表中的所有任务执行完毕之后,返回所有任务的结果组成的列表,此时列表中所有的Future中的isDone均为true,表示所有任务均被执行。如果某个任务执行出现异常,或因时限期满而返回,isDone仍然为true,但Future状态分别为3和6(后续会解释)
 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException;
 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit) throws InterruptedException;
  1. AbstractExecutorService 与 ScheduledExecutorService
    AbstractExecutorService 是一个抽象类,实现了ExecutorService接口。这是ExecutorService的默认实现,我们来看下AbstractExecutorService中实现的方法:
    在这里插入图片描述
    并未对ExecutorService接口做扩展,实现了submit方法与invoke系列方法,这里只简单看下submit方法。
    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }

    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }

    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

	protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }
    
    /**
     * 将入参任务封装成了FutureTask,而FutureTask的run方法是自带异常捕捉的,这就是为什么execute直接抛出异常,submit没有直接抛出异常的原因。
     * https://juejin.cn/post/6844904071577468935
     */
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }

ScheduledExecutorService 继承 ExecutorService接口,额外定义了一些定时执行任务的操作接口。
在这里插入图片描述

/**
 * 在给定的延迟时间delay后,执行任务command,仅执行一次.
 * 返回一个代表任务结果的ScheduledFuture,入参为Runnable,所以该ScheduledFuture的get方法只返回null
 */ 
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);

/**
 * 同上,区别仅在于入参不同,所以返回值ScheduledFuture的get方法可获取到非空值
 */
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);
  1. ThreadPoolExecutor 以及 ScheduledThreadPoolExecutor

https://www.jianshu.com/nb/24061051
https://www.jianshu.com/p/c41e942bcd64
https://www.jianshu.com/p/f030aa5d7a28

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值