Java ~ Executor ~ ExecutorService【源码】

前言


 文章

一 ExecutorService(执行器服务)接口及机制详解


 类

    如果说Executor(执行器)接口作为执行框架最顶级,其作用是明确了执行器框架的核心目标:将任务的递交与执行分离(并负责执行),那ExecutorService (执行器服务)接口的作用就是完善/拓展这个目标。执行器服务是一个功能更加广泛的接口,作为执行器接口的子接口,其在原有的基础上新增了关闭、终止及结果等概念,更加贴合实际的使用需求,因此在实际的开发中,我们往往会使用执行器服务接口的变量来承接具体的执行器实例,而非执行器接口。

  • 关闭:被关闭后的执行器无法接受新递交的任务,并可自我选择是否阻止未完成的任务(即关闭前递交的,还未执行和执行中的任务)继续执行,用于执行器的内部管理;
  • 终止:终止的前提是关闭,用于表现在执行器终止后未完成任务的整体执行状态;
  • 结果:在执行器的递交基础上新增了返回值,用于监控任务的执行状态并获取任务的执行结果;
  • 类型:支持新的Callable(可调用的)接口类型的任务,在对结果的支持上更加方便;
  • 批量:支持任务的批量执行,用于提升任务的递交及执行效率。
/**
 * An {@link Executor} that provides methods to manage termination and methods that can produce a {@link Future} for tracking
 * progress of one or more asynchronous tasks.
 * Executor提供管理终止的方法,以及可以产生Future的方法用于追踪一个或多个异步任务的进度。
 * <p>
 * An {@code ExecutorService} can be shut down, which will cause it to reject new tasks. Two different methods are provided for
 * shutting down an {@code ExecutorService}. The {@link #shutdown} method will allow previously submitted tasks to execute
 * before terminating, while the {@link #shutdownNow} method prevents waiting tasks from starting and attempts to stop currently
 * executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks
 * can be submitted. An unused {@code ExecutorService} should be shut down to allow reclamation of its resources.
 * ExecutorService可以关闭,这将导致它拒绝新任务。有两个不同的方法用于关闭一个ExecutorService。shutdown()方法允许之前
 * 递交的任务在终止之前执行,而shutdownNow()方法阻止等待中的任务开始并企图停止当前执行中的任务【Java中没有强迫式中断,
 * 因此shutdownNow()方法只是企图停止,能否停止需要看任务能否响应,如果不能则还是会在执行完成后关闭】。在终止时,
 * Executor不存在正在执行的任务,没有任务等待执行,且没有新任务能够递交。一个不使用的ExecutorService应该关闭以允许它的
 * 资源再利用。
 * <p>
 * Method {@code submit} extends base method {@link Executor#execute(Runnable)} by creating and returning a {@link Future}
 * that can be used to cancel execution and/or wait for completion. Methods {@code invokeAny} and {@code invokeAll} perform
 * the  most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to
 * complete.
 * (Class {@link ExecutorCompletionService} can be used to write customized variants of these methods.)
 * submit()方法拓展自基础方法Executor.execute(Runnable),通过创建和返回一个Future能够用于取消执行和/或等待其完成。方法
 * invokeAny()和invokeAll()执行最常用的批量执行形式,执行一组任务,然后等待至少一个或全部任务完成。
 * <p>
 * The {@link Executors} class provides factory methods for the executor services provided in this package.
 * Executors类为这个包中提供的ExecutorService提供工厂方法(不推荐用!不推荐用!不推荐用!重要的事情说三遍!!!)。
 *
 * <h3>Usage Examples</h3>
 * <h3>使用案例</h3>
 * <p>
 * Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured
 * {@link Executors#newFixedThreadPool} factory method:
 * 这是一个网络服务的草图,线程池中的线程服务传入的请求。它使用了预配置的Executors.newFixedThreadPool()工厂方法:
 * <pre> {@code
 * class NetworkService implements Runnable {
 *
 *     // 服务套接字
 *     private final ServerSocket serverSocket;
 *     // 线程池
 *     private final ExecutorService pool;
 *
 *     public NetworkService(int port, int poolSize) throws IOException {
 *         // 构造函数,传入套接字和线程池大小。
 *         serverSocket = new ServerSocket(port);
 *         // 通过Executors.newFixedThreadPool()方法创建一个指定队列容量的线程池。
 *         pool = Executors.newFixedThreadPool(poolSize);
 *     }
 *
 *     public void run() {
 *         // run the service
 *         try {
 *             // 通过serverSocket.accept()方法不断循环的接收请求,并交由线程池进行处理。
 *             for (;;) {
 *                 pool.execute(new Handler(serverSocket.accept()));
 *             }
 *         } catch (IOException ex) {
 *             pool.shutdown();
 *         }
 *     }
 *
 * }
 *
 * class Handler implements Runnable {
 *
 *     // 套接字
 *     private final Socket socket;
 *
 *     Handler(Socket socket) { this.socket = socket; }
 *
 *     public void run() {
 *         // 从套接字中获取请求。
 *         // read and service request on socket
 *     }
 * }}</pre>
 * <p>
 * The following method shuts down an {@code ExecutorService} in two phases, first by calling {@code shutdown} to reject
 * incoming tasks, and then calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:
 * 以下方法分两个阶段关闭ExecutorService,首先调用shutdown()拒绝传入的任务,然后如果必要,调用shutdownNow()方法,以
 * 取消所有驻留的任务:
 * <pre> {@code
 * void shutdownAndAwaitTermination(ExecutorService pool) {
 *     // Disable new tasks from being submitted
 *     // 禁止递交新任务。
 *     pool.shutdown();
 *     try {
 *         // Wait a while for existing tasks to terminate
 *         // 等待一段时间,等待线程池终止。
 *         if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
 *              // Cancel currently executing tasks
 *              // 取消当前执行的任务。
 *             pool.shutdownNow();
 *             // Wait a while for tasks to respond to being cancelled
 *             // 等待一段时间,等待线程池终止。
 *             if (!pool.awaitTermination(60, TimeUnit.SECONDS))
 *                 // 打印线程池没有关闭。
 *                 System.err.println("Pool did not terminate");
 *         }
 *       } catch (InterruptedException ie) {
 *           // (Re-)Cancel if current thread also interrupted
 *           // 如果当前线程也中断,取消。
 *           pool.shutdownNow();
 *           // Preserve interrupt status
 *           // 维持中断状态。
 *          Thread.currentThread().interrupt();
 *   }
 * }}</pre>
 *
 * <p>
 * Memory consistency effects: Actions in a thread prior to the submission of a {@code Runnable} or {@code Callable} task to
 * an {@code ExecutorService} <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> any actions taken
 * by that task, which in turn <i>happen-before</i> the result is retrieved via {@code Future.get()}.
 * 内存一致性的影响:在向ExecutorService提交Runnable或Callable任务之前,线程中的操作发生在该任务执行任何操作之前(即
 * 程序中在递交任务之前代码会在递交之前完成),而该任务执行的操作又发生在通过Future.get()检索结果之前(即递交之后的代
 * 码会在Future.get()执行)。
 *
 * @author Doug Lea
 * @Description: 执行器服务接口
 * @since 1.5
 */
public interface ExecutorService extends Executor {
   ...
}

 方法

  • void shutdown() —— 关闭 —— 关闭当前执行器,关闭后当前执行器会拒绝新任务递交,但不会取消旧(等待中/执行中)任务。方法不会等待所有的旧任务执行结束(完成/异常/取消)后返回。
    /**
     * Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
     * Invocation has no additional effect if already shut down.
     * 发起有序关闭,之前递交的任务可以执行,但不接受新的任务。如果已经关闭则调用没有额外效果。
     * <p>
     * This method does not wait for previously submitted tasks to complete execution. Use {@link #awaitTermination
     * awaitTermination} to do that.
     * 该方法不等待之前递交的任务完成执行【即不会等到所有的任务都执行完成后再返回】。使用awaitTermination()方法做这件
     * 事【等待所有的任务都执行完成】。
     *
     * @throws SecurityException if a security manager exists and shutting down this ExecutorService may manipulate threads
     *                           that the caller is not permitted to modify because it does not hold {@link RuntimePermission}{@code
     *                           ("modifyThread")}, or the security manager's {@code checkAccess} method denies access.
     *                           安全异常:如果存在安全管理器并且关闭此ExecutorService可能会操作调用方不允许修改的线程,因为
     *                           它不包含"modifyThread"(权限)或安全管理器的checkAccess方法拒绝访问。
     * @Description: 名称:关闭
     * @Description: 作用:关闭当前执行器,关闭后当前执行器会拒绝新任务递交,但不会取消旧(等待中/执行中)任务。方法
     * @Description: 不会等待所有的旧任务执行完成后返回。
     * @Description: 逻辑:~
     */
    void shutdown();
  • List shutdownNow() —— 立即关闭 —— 关闭当前执行器,关闭后当前执行器会拒绝新任务递交,并会阻止等待中的旧任务执行,且会尝试中断执行中的旧任务,最后返回未执行(等待中)的旧任务列表。方法不会等待执行中的旧任务执行结束(完成/异常/取消)后返回。
    /**
     * Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that
     * were awaiting execution.
     * 尝试停止所有正在积极执行的任务【相应中断】,阻止等待的任务执行,并返回等待执行的任务列表。
     * <p>
     * This method does not wait for actively executing tasks to terminate.  Use {@link #awaitTermination awaitTermination} to
     * do that.
     * 该方法不等待正在积极执行的任务终止。使用awaitTermination()方法做这件事。
     * <p>
     * There are no guarantees beyond best-effort attempts to stop processing actively executing tasks.  For example, typical
     * implementations will cancel via {@link Thread#interrupt}, so any task that fails to respond to interrupts may never
     * terminate.
     * 除尽最大努力尝试停止处理执行的任务之外它们不做任何保证【即无法保证该方法运行后,正在执行的任务会被中断,毕竟
     * Java并没有提供强制中断的机制,只有响应式中断的机制,即需要开发者在代码中加入相应代码中断的逻辑】。例如,典型
     * 的实现将通过线程中断来取消(任务),所以任何响应中断失败的任务可能永远不能终结。
     *
     * @return list of tasks that never commenced execution 从未开始执行的任务列表
     * @throws SecurityException if a security manager exists and shutting down this ExecutorService may manipulate threads
     *                           that the caller is not permitted to modify because it does not hold {@link RuntimePermission}{@code
     *                           ("modifyThread")}, or the security manager's {@code checkAccess} method denies access.
     *                           安全异常:如果存在安全管理器并且关闭此ExecutorService可能会操作调用方不允许修改的线程,因为
     *                           它不包含"modifyThread"(权限)或安全管理器的checkAccess方法拒绝访问。
     * @Description: 名称:立刻关闭
     * @Description: 作用:关闭当前执行器,关闭后当前执行器会拒绝新任务递交,并会阻止等待中的旧任务执行,且会尝试取消
     * @Description: 执行中的旧任务,最后返回未执行(等待中)的旧任务列表。方法不会等待执行中的旧任务执行取消/完成后
     * @Description: 返回。
     * @Description: 逻辑:~
     */
    List<Runnable> shutdownNow();
  • boolean isShutdown() —— 是否关闭 —— 判断当前执行器是否关闭,是则返回true;否则返回false。
    /**
     * Returns {@code true} if this executor has been shut down.
     * 如果当前执行器已被关闭则返回真。
     *
     * @return {@code true} if this executor has been shut down 如果当前执行器已被关闭则返回真。
     * @Description: 名称:是否关闭
     * @Description: 作用:判断当前执行器是否关闭,是则返回true;否则返回false。
     * @Description: 逻辑:~
     */
    boolean isShutdown();
  • boolean isTerminated() —— 是否终止 —— 判断当前执行器是否终止,即判断当前执行器是否关闭且所有旧任务都执行结束(完成/异常/取消),是则返回true;否则返回false。由于关闭是终止的前提,因此该方法只会在先调用shutdown()或shutdownNow()方法之后调用才有可能返回true。
    /**
     * Returns {@code true} if all tasks have completed following shut down. Note that {@code isTerminated} is never {@code true}
     * unless either {@code shutdown} or {@code shutdownNow} was called first.
     * 如果在关闭之后所有的任务完成则返回真。注意,除非先调用shutdown()或shutdownNow()方法,否则isTerminated()方法是永远
     * 不会返回真的。
     *
     * @return {@code true} if all tasks have completed following shut down  如果在关闭之后所有的任务完成则返回真
     * @Description: 名称:是否终止
     * @Description: 作用:判断当前执行器是否终止,即判断当前执行器关闭且所有旧任务都执行完成,是则返回true;否则返回false。
     * @Description: 由于关闭是终止的前提,因此该方法只会在先调用shutdown()或shutdownNow()方法之后调用才有可能返回true。
     * @Description: 逻辑:~
     */
    boolean isTerminated();
  • boolean awaitTermination(long timeout, TimeUnit unit) —— 等待终止 —— 等待当前执行器终止。如果在指定等待时间内当前执行器终止则返回true;否则返回false。
    /**
     * Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is
     * interrupted, whichever happens first.
     * 阻塞,直到所有任务在关闭请求后完成执行,或发生超时,或当前线程被中断(以先发生的情况为准)。
     *
     * @param timeout the maximum time to wait 用于等待最大值时间
     * @param unit    the time unit of the timeout argument 超时参数的时间单位
     * @return {@code true} if this executor terminated and {@code false} if the timeout elapsed before termination
     * 如果执行器终止则返回真,如果在终止之前超时则返回假。
     * @throws InterruptedException if interrupted while waiting
     *                              中断异常:如果在等待中中断
     * @Description: 名称:等待终止
     * @Description: 作用:等待当前执行器终止。如果在指定等待时间内当前执行器终止则返回true;否则返回false。
     * @Description: 逻辑:~
     */
    boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
  • Future submit(Callable task) —— 递交 —— 向当前执行器递交指定可回调/任务,并返回追踪/获取可回调/任务执行状态/结果/异常的未来。
    /**
     * Submits a value-returning task for execution and returns a Future representing the pending results of the task. The Future's
     * {@code get} method will return the task's result upon successful completion.
     * 递交一个存在返回值的任务用于执行,并返回一个未来代表任务的待定结果。这个未来的get()方法会在「任务」成功完成之后返
     * 回任务结果【在任务完成之前执行未来的get()方法的线程会陷入阻塞】。
     * <p>
     * If you would like to immediately block waiting for a task, you can use constructions of the form
     * {@code result = exec.submit(aCallable).get();}
     * 如果你想立即阻塞等待一个任务,你可以使用result = exec.submit(aCallable).get();结构。
     * <p>
     * Note: The {@link Executors} class includes a set of methods that can convert some other common closure-like objects, for
     * example, {@link java.security.PrivilegedAction} to {@link Callable} form, so they can be submitted.
     * 注意:Executors类包含一组能够转变一些其他常见的闭包对象的方法(例如将PrivilegedAction变为Callable形式),因此它们可
     * 以递交。
     *
     * @param task the task to submit 用于递交的任务
     * @param <T>  the type of the task's result 任务的结果类型
     * @return a Future representing pending completion of the task 一个代表任务待定完成的未来
     * @throws RejectedExecutionException if the task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任务无法安排执行
     * @throws NullPointerException       if the task is null
     *                                    空指针异常:如果任务为空
     * @Description: 名称:递交
     * @Description: 作用:向当前执行器递交可回调任务,并返回追踪/获取可回调任务执行状态/结果的未来。
     * @Description: 逻辑:~
     */
    <T> Future<T> submit(Callable<T> task);
  • Future submit(Runnable task, T result) —— 递交 —— 向当前执行器递交指定可运行/任务,并返回追踪/获取可运行/任务执行状态/结果/异常的未来。递交可运行/任务时会同步传入一个用于承载可运行/任务执行结果/异常的变量,该变量承载的可运行/任务执行结果/异常即可直接获取(即直接通过result(结果)参数获取),也会向未来传递,因此该方法返回的未来的get()方法可返回可运行/任务执行结果/异常。
    /**
     * Submits a Runnable task for execution and returns a Future representing that task. The Future's {@code get} method will
     * return the given result upon successful completion.
     * 递交一个可运行任务用于执行,并返回一个代表任务的未来。该未来的get()方法将在「任务」成功完成之后返回指定的结果。
     *
     * @param task   the task to submit 用于递交的任务
     * @param result the result to return 返回的结果
     * @param <T>    the type of the result 结果的类型
     * @return a Future representing pending completion of the task 一个代表任务待定完成的未来
     * @throws RejectedExecutionException if the task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任务无法安排执行
     * @throws NullPointerException       if the task is null
     *                                    空指针异常:如果任务为空
     * @Description: 名称:递交
     * @Description: 作用:向当前执行器递交可运行任务,并返回追踪/获取可运行任务执行状态/结果的未来。递交可运行任务时会
     * @Description: 同步传入一个用于承载可运行任务执行结果的变量,该变量承载的可运行任务执行结果即可直接获取【即直接通
     * @Description: 过result(结果)参数获取】,也会向未来传递,因此该方法返回的未来的get()方法可返回可运行任务执行结果。
     * @Description: 逻辑:~
     */
    <T> Future<T> submit(Runnable task, T result);
  • Future<?> submit(Runnable task) —— 递交 —— 向当前执行器递交指定可运行/任务,并返回追踪/获取可运行/任务执行状态/结果/异常的未来。由于在递交可运行/任务时没有传入用于承载可运行/任务执行结果/异常的变量,因此未来无法获取结果/异常的执行结果/异常,故而该方法返回的未来的get()方法将永远返回null。
    /**
     * Submits a Runnable task for execution and returns a Future representing that task. The Future's {@code get} method will
     * return {@code null} upon <em>successful</em> completion.
     * 递交一个可运行任务用于执行,并返回一个代表任务的未来。这个未来的get()方法将在(任务)成功完成之后返回null【因此使
     * 用该方法的前提是不在意返回结果】
     *
     * @param task the task to submit 用于递交的任务
     * @return a Future representing pending completion of the task 一个代表任务待定完成的未来
     * @throws RejectedExecutionException if the task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任务无法安排执行
     * @throws NullPointerException       if the task is null
     *                                    空指针异常:如果任务为空
     * @Description: 名称:递交
     * @Description: 作用:向当前执行器递交可运行任务,并返回追踪/获取可运行任务执行状态/结果的未来。由于在递交可运行任
     * @Description: 务时没有传入用于承载可运行任务执行结果的变量,因此未来无法获取可运行任务的执行结果,故而该方法返回
     * @Description: 的未来的get()方法将永远返回null。
     * @Description: 逻辑:~
     */
    Future<?> submit(Runnable task);
  • List<Future> invokeAll(Collection<? extends Callable> tasks) throws InterruptedException —— 调用所有 —— 向当前执行器递交指定可调用/任务集,并返回追踪/获取可调用任务执行状态/结果/异常的未来集。该方法会等待至递交的可调用/任务集全部执行结束(完成/异常/取消),因此返回的未来集中每个未来的isDone()方法结果都为true。
    /**
     * Executes the given tasks, returning a list of Futures holding their status and results when all complete.
     * {@link Future#isDone} is {@code true} for each element of the returned list. Note that a <em>completed</em> task could
     * have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection
     * is modified while this operation is in progress.
     * 执行指定的任务集,当全部完成时返回一个持有它们状态和结果的未来列表。未来的isDone()方法对于返回列表中的每个元素/未
     * 来都为真【即该方法会在指定任务集全部完成后返回,因此可知该方法在执行期间必然时阻塞的)。注意:一个完成的任务可以
     * 是正常终止,也可以是通过抛出异常终止。当该操作进行时如果指定集被修改,则方法的结果集是未定义的【即在方法执行的过
     * 程中如果对任务集进行修改可能会导致无法产生正确的结果集】。
     *
     * @param tasks the collection of tasks 任务集
     * @param <T>   the type of the values returned from the tasks 返回的任务集的值类型
     * @return a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task
     * list, each of which has completed
     * 一个代表任务集的未来列表,顺序与指定任务列表产生的迭代器一致,每一个未来都是已完成的。
     * @throws InterruptedException       if interrupted while waiting, in which case unfinished tasks are cancelled
     *                                    中断异常:如果等待时中断,这种情况下未完成(等待中/执行中)的任务将被取消
     * @throws NullPointerException       if tasks or any of its elements are {@code null}
     *                                    空指针异常:如果任务集或任何元素为null
     * @throws RejectedExecutionException if any task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任意任务无法被安排执行
     * @Description: 名称:调用所有
     * @Description: 作用:向当前执行器递交可回调任务集,并返回追踪/获取可回调任务执行状态/结果的未来集。该方法会等待至
     * @Description: 递交的可回调任务集全部正常/异常的执行完成,因此返回的未来集中每个未来的isDone()方法结果都为true。
     * @Description: 逻辑:~
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException;
  • List<Future> invokeAll(Collection<? extends Callable> tasks, long timeout, TimeUnit unit) throws InterruptedException —— 调用所有 —— 向当前执行器递交指定可调用/任务集,并返回追踪/获取可调用/任务执行状态/结果/异常的未来集。该方法会在指定等待时间内等待递交的可调用/任务集执行结束(完成/异常/取消),如果超时则会取消其中未结束(等待中/执行中)的可调用/任务。由于Java是响应式中断,因此具体表现为等待中的可调用/任务不会再执行,而执行中的可调用/任务如果成功响应则取消;否则任由其继续执行,即不在乎具体的取消结果,因此返回的未来集中每个未来的isDone()方法结果都为true。
    /**
     * Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires,
     * whichever happens first. {@link Future#isDone} is {@code true} for each element of the returned list.Upon return, tasks that
     * have not completed are cancelled. Note that a <em>completed</em> task could have terminated either normally or by throwing
     * an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.
     * 执行指定的任务集,当全部完成或超时(不论哪一个先发生)时返回一个持有它们状态和结果的未来列表。未来的isDone()方法对
     * 于每个返回列表中的每个元素/未来都为真。当返回时,任务集中未被完成的任务将被取消。注意:一个完成的任务可以正常终止,
     * 也可以是通过抛出异常终止。当该操作进行时如果指定集被修改,则方法的结果集是未定义的【即在方法执行的过程中如果对任务
     * 集进行修改可能会导致无法产生正确的结果集】。
     *
     * @param tasks   the collection of tasks 任务集
     * @param timeout the maximum time to wait 用于等待的最大时间
     * @param unit    the time unit of the timeout argument 超时参数的单位
     * @param <T>     the type of the values returned from the tasks 返回的任务集的值类型
     * @return a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task
     * list. If the operation did not time out, each task will have completed. If it did time out, some of these tasks will not have
     * completed.
     * 一个代表任务集的未来列表,顺序与指定任务列表产生的迭代器一致。如果操作未超时,则每个任务都是已完成的。如果超时,则
     * 会有一些任务未完成。
     * @throws InterruptedException       if interrupted while waiting, in which case unfinished tasks are cancelled
     *                                    中断异常:如果等待时中断,这种情况下未完成(等待中/执行中)的任务将被取消
     * @throws NullPointerException       if tasks or any of its elements are {@code null}
     *                                    空指针异常:如果任务集或任何元素为null
     * @throws RejectedExecutionException if any task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任意任务无法被安排执行
     * @Description: 名称:调用所有
     * @Description: --------------------------------------------------------------------------------------------------------------------------------------
     * @Description: 作用:向当前执行器递交可调用/任务集,并返回追踪/获取可调用/任务执行状态/结果的未来集。该方法会在
     * @Description: 指定等待时间内等待指定的可调用/任务集中的调用/任务结束(完成/异常/取消),如果超时则会取消其中未
     * @Description: 结束(等待中/执行中)的可调用/任务,因此返回的未来集中每个未来的isDone()方法结果都为true。由于Java
     * @Description: 是响应式中断,因此具体表现为等待中的可调用/任务不会再执行,而执行中的可调用/任务如果成功响应则取
     * @Description: 消;否则(无法/失败响应)任由其继续执行,即不在乎具体的取消结果。
     * @Description: --------------------------------------------------------------------------------------------------------------------------------------
     * @Description: 逻辑:~
     * @Description: --------------------------------------------------------------------------------------------------------------------------------------
     * @Description: 注意:~
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException;
  • T invokeAny(Collection<? extends Callable> tasks) throws InterruptedException, ExecutionException —— 调用任意 —— 向当前执行器递交指定可调用/任务集,并返回其中一个成功完成的可调用/任务的执行结果。该方法会等待至递交的可调用/任务集中的一个执行完成(异常/取消不计算在内),其余未结束(等待中/执行中)的可调用/任务将被取消。由于Java是响应式中断,因此具体表现为等待中的可调用/任务不会再执行,而执行中的可调用/任务如果成功响应则取消;否则任由其继续执行,即不在乎具体的取消结果。而如果所有的可调用/任务都执行失败(异常/取消)则会抛出执行异常。
    /**
     * Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if
     * any do. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are
     * undefined if the given collection is modified while this operation is in progress.
     * 执行指定的任务集,如果已经有任务执行完成,返回一个已经成功完成的结果(在没有抛出异常的情况下)。当正常及异常时返回
     * 后,任务集中未执行的任务将被取消【即只要成功一个,后续的任务就将被取消】。当该操作进行时如果指定集被修改,则方法的
     * 结果集是未定义的【即在方法执行的过程中如果对任务集进行修改可能会导致无法产生正确的结果集】。
     *
     * @param tasks the collection of tasks 任务集
     * @param <T>   the type of the values returned from the tasks 从任务集中返回的值的类型
     * @return the result returned by one of the tasks 返回任务中一个结果
     * @throws InterruptedException       if interrupted while waiting
     *                                    中断异常:如果在等待时中断
     * @throws NullPointerException       if tasks or any element task subject to execution is {@code null}
     *                                    空指针异常:如果要执行的任务集或任意元素为null
     * @throws IllegalArgumentException   if tasks is empty
     *                                    非法参数异常:如果任务集为空
     * @throws ExecutionException         if no task successfully completes
     *                                    执行异常:如果没有成功执行的任务
     * @throws RejectedExecutionException if any task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任意任务无法被安排执行
     * @Description: 名称:调用任意
     * @Description: 作用:向当前执行器递交可回调任务集,并返回其中一个成功执行的可回调任务的执行结果。该方法会等待至递交
     * @Description: 的可回调任务集中的一个正常执行完成(异常/取消不计算在内),其余未完成(等待中/执行中)的任务将被取消。
     * @Description: 由于Java是响应式中断,因此具体表现为等待中的任务不会再执行,而执行中的任务如果成功响应取消则取消;否
     * @Description: 则(无法/失败响应)任由其继续执行。
     * @Description: 逻辑:~
     */
    <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;
  • T invokeAny(Collection<? extends Callable> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException —— 调用任意 —— 向当前执行器递交指定可调用/任务集,并返回其中一个成功完成的可调用/任务的执行结果。该方法会在指定等待时间内等待递交的可调用/任务集中的一个执行完成(异常/取消不计算在内)。最终无论是否超时,其余未结束(等待中/执行中)的可调用/任务都将被取消。由于Java是响应式中断,因此具体表现为等待中的可调用/任务不会再执行,而执行中的可调用/任务如果成功响应则取消;否则任由其继续执行,即不在乎具体的取消结果。在指定等待时间内,如果所有的可调用/任务都执行失败(异常/取消)则会抛出执行异常;而超时则会抛出超时异常。
    /**
     * Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if
     * any do before the given timeout elapses. Upon normal or exceptional return, tasks that have not completed are cancelled. The
     * results of this method are undefined if the given collection is modified while this operation is in progress.
     * 执行指定的任务集,返回一个已经成功完成的结果(在没有抛出异常的情况下),如果在超时之前已经有任务执行完成。当正常及
     * 异常时返回,任务集中未执行的任务将被取消(即只要成功一个,后续的任务就将被取消)。当该操作进行时如果指定集被修改,
     * 则方法的结果集是未定义的【即在方法执行的过程中如果对任务集进行修改可能会导致无法产生正确的结果集】。
     *
     * @param tasks   the collection of tasks 任务集
     * @param timeout the maximum time to wait 最大超时时间
     * @param unit    the time unit of the timeout argument 超时时间单位
     * @param <T>     the type of the values returned from the tasks 从任务集中返回的值的类型
     * @return the result returned by one of the tasks 任务中一个结果
     * @throws InterruptedException       if interrupted while waiting
     *                                    中断异常:如果在等待时中断
     * @throws NullPointerException       if tasks or any element task subject to execution is {@code null}
     *                                    空指针异常:如果要执行的任务集或任意元素为null
     * @throws TimeoutException           if the given timeout elapses before any task successfully completes
     *                                    超时:如果在任意任务成功完成之前超时
     * @throws ExecutionException         if no task successfully completes
     *                                    执行异常:如果没有成功执行的任务
     * @throws RejectedExecutionException if any task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任意任务无法被安排执行
     * @Description: 名称:调用任意
     * @Description: 作用:向当前执行器递交可回调任务集,并返回其中一个成功执行的可回调任务的执行结果。该方法会在指定等待
     * @Description: 时间内等待递交的可回调任务集中的一个正常执行完成(异常/取消不计算在内),最终无论是否超时。未完成(
     * @Description: 等待中/执行中)的任务都将被取消。由于Java是响应式中断,因此具体表现为等待中的任务不会再执行,而执行
     * @Description: 中的任务如果成功响应取消则取消;否则(无法/失败响应)任由其继续执行。与常规的定时方法不同,该方法超
     * @Description: 时时会抛出超时异常。
     * @Description: 逻辑:~
     */
    <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

说淑人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值