ExcutorService源码解析

本文详细介绍了ExecutorService接口的功能和使用方法,包括如何提交任务、管理任务执行、停止服务等。此外,还提供了网络服务中线程池的具体应用实例。

ExcutorService

/**
 * Create by ~JH~ on 2018/4/9
 */
import java.util.List;
import java.util.Collection;
import java.util.concurrent.*;

/**
 *ExcutorService可以停止,这个操作会导致拒绝生产新的任务。
 * 两个不同的方法提供停止一个ExcutorService,shutdown()方法会允许之前提交的任务在终止之前执行。
 * shutdownNow()阻止等待的任务开始或者试图停止当前正在执行的任务。
 * 终止的时候,一个Excutor没有活跃的任务执行。没有任务等待执行,没有新的任务被提交。
 *一个没有使用的ExcutorService应该关闭以允许资源回收利用。
 *
 *submit()方法是继承自Excutor#Excute(Runnable)通过创建和返回一个Future,这个可以用来取消执行或者等待完成。
 * invokeAll()和invokeAny()被使用的最多,执行多个任务然后等待至少一个或者所有的任务完成。
 * ExcutorCompiletionService可以被使用在写为某些方法定制的变量上。
 *
 * <p>The {@link Executors} class provides factory methods for the
 * executor services provided in this package.
 *
 * <h3>Usage Examples</h3>
 *
 *接下来是一些关于网络服务的描述党请求到达时线程在线程池中会使用提前配置的Excutor#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);
 *     pool = Executors.newFixedThreadPool(poolSize);
 *   }
 *
 *   public void run() { // run the service
 *     try {
 *       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>
 *
 *这个方法的停止包括两步,拒绝进来的任务(调用shutdown()),然后调用(shutdownnow())
 * 如果可能取消逗留的任务
 *  <pre> {@code
 * void shutdownAndAwaitTermination(ExecutorService pool) {
 *   pool.shutdown(); // Disable new tasks from being submitted未提交的任务停止
 *   try {
 *     // Wait a while for existing tasks to terminate等待一会儿以便结束操作让任务退出
 *     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
 *       pool.shutdownNow(); // Cancel currently executing tasks取消当前执行的任务
 *       // 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()}.
 *内存一致性影响:
 * 任何在那个任务中发生的行为,都一次可以恢复通过Future.get()
 * @since 1.5
 * @author Doug Lea
 */
public interface ExecutorService extends Executor {

    /**
     *初始化一个有序的shutdown将先前的已提交的任务执行,但是不会有任务再次被接受。
     * 如果已经停止,这个操作没有其他的影响
     *
     *这个方法不会等待先前的已提交的任务执行完成,会使用 #awaitTermination awaitTermination去完成
     *
     * @throws SecurityException
     *如果一个安全的管理者退出并且停止当前的ExcutorService可能会操作那些线程的调用者没有被允许修改的线程因为他们没有RuntimePermission或者安全管理者的拒绝接入
     *
     */
    void shutdown();

    /**
     *尝试停止所有活跃的正在执行的任务,停止等待中的任务,并且返回一列正在等待执行的任务
     *这个方法不会等待活跃的正在执行的任务结束,而是使用#awaitTermination awaitTermination}去做
     *不会保证在最大的努力之外尝试停止活跃的正在执行的任务。例如,
     * 典型的实现将会取消,许多任务会相应中断失败可能没有终止。
     * @return list of tasks that never commenced execution没有执行的任务的list
     * @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
     *         java.lang.RuntimePermission}{@code ("modifyThread")},
     *         or the security manager's {@code checkAccess} method
     *         denies access.
     */
    List<Runnable> shutdownNow();

    /**
     * Returns {@code true} if this executor has been shut down.
     *已经终止就返回True
     * @return {@code true} if this executor has been shut down
     */
    boolean isShutdown();

    /**
     * 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.
     *
     * @return {@code true} if all tasks have completed following shut down
     */
    boolean isTerminated();

    /**
     *阻塞到所有的任务都已经完成在一个shutdown请求之后,或者超市发生,或者当前的线程被中断,无论其中那个最先发生
     * @param timeout the maximum time to wait最大等待时间
     * @param unit the time unit of the timeout argument时间单元 秒 分 时
     * @return {@code true} if this executor terminated executor终止返回true
     *         {@code false} if the timeout elapsed before termination在终止之前超时返回false
     * @throws InterruptedException if interrupted while waiting
     */
    boolean awaitTermination(long timeout, TimeUnit unit)
            throws InterruptedException;

    /**
     *提交一个有返回值的任务执行并且返回一个代表这个任务的不确定的结果。
     * Future#get方法将会返回这个任务的结果在成功执行之前
     *如果对于一个任务你想立即阻塞等待,你可以使用这种结构result = exec.submit(aCallable).get();
     *Executor类包括一套包含了转换一些普通closure-like对象成为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
     */
    <T> Future<T> submit(Callable<T> task);

    /**
     *提交一个Runnable的任务去执行,并且返回一个代表这个任务的Future
     * 这个Future的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
     */
    <T> Future<T> submit(Runnable task, T result);

    /**
     *在成功之前会返回null
     * @param task the task to submit
     * @return a Future representing pending completion of the task代表待完成的任务的Future
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if the task is null
     */
    Future<?> submit(Runnable task);

    /**
     *执行所有提供的任务,当所有的都完成了返回一个Future列表包括他们的状态和结果
     *一个完成的任务可能是正常结束或者是抛出异常
     * @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
     *         返回一个Futrue的集合,以和task执行相同的次序,每一个任务都被完成
     * @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}
     * @throws RejectedExecutionException if any task cannot be
     *         scheduled for execution
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
            throws InterruptedException;

    /**
     *执行任务后,当所有的都被完成或者超时都会返回一个Future的集合来保存他们的状态和结果。
     * future的isDone都会返回true。返回结果的时候,没有完成的任务会调用cancel方法
     * 标记完成的任务应该正常结束或者是抛出一个异常。返回的结果是不确定的如果给的集合在操作过程中被改变了。
     * @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, any of its elements, or
     *         unit are {@code null}
     * @throws RejectedExecutionException if any task cannot be scheduled
     *         for execution
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                  long timeout, TimeUnit unit)
            throws InterruptedException;

    /**
     *执行给的任务集返回成功执行的结果,当正常或者异常被返回的时候,
     * 所有的未完成的任务都会被取消。这个返回的结果是不确定的日过参数的集合在运行时被改变
     * @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}
     * @throws IllegalArgumentException if tasks is empty
     * @throws ExecutionException if no task successfully completes
     * @throws RejectedExecutionException if tasks cannot be scheduled
     *         for execution
     */
    <T> T invokeAny(Collection<? extends Callable<T>> tasks)
            throws InterruptedException, ExecutionException;

    /**
     *执行给的任务集返回成功执行的结果,如果在超时之前。
     * 当正常或者异常被返回的时候,所有的未完成的任务都会被取消。
     * 这个返回的结果是不确定的日过参数的集合在运行时被改变
     * @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 unit, or any element
     *         task subject to execution is {@code null}
     * @throws TimeoutException if the given timeout elapses before
     *         any task successfully completes
     * @throws ExecutionException if no task successfully completes
     * @throws RejectedExecutionException if tasks cannot be scheduled
     *         for execution
     */
    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值