/** * 执行提交{@link Runnable}任务的对象 * 此接口提供了一种将任务提交与每个任务的运行机制分离的方法: 包括线程使用、调度等的详细信息 * (使用时)通常使用{@code Executor},而不是显式创建线程 * * 例如,与其为一组任务调用: * new Thread(new RunnableTask().start() * new Thread(new RunnableTask().start() * new Thread(new RunnableTask().start() * 不如使用: * Executor executor = anExecutor(); * executor.execute(new RunnableTask1()); * executor.execute(new RunnableTask2()); * * An object that executes submitted {@link Runnable} tasks. This * interface provides a way of decoupling task submission from the * mechanics of how each task will be run, including details of thread * use, scheduling, etc. An {@code Executor} is normally used * instead of explicitly creating threads. For example, rather than * invoking {@code new Thread(new RunnableTask()).start()} for each * of a set of tasks, you might use: * * <pre> {@code * Executor executor = anExecutor(); * executor.execute(new RunnableTask1()); * executor.execute(new RunnableTask2()); * ...}</pre> * * 但是{@code Executor}接口并不严格要求执行是异步的 * 在最简单的情况下,执行器可以在调用线程中立即运行提交的任务: * * class DirectExecutor implements Executor { * public void execute(Runnable r) { * r.run(); * } * * However, the {@code Executor} interface does not strictly require * that execution be asynchronous. In the simplest case, an executor * can run the submitted task immediately in the caller's thread: * * <pre> {@code * class DirectExecutor implements Executor { * public void execute(Runnable r) { * r.run(); * } * }}</pre> * * 更经典的使用是: 任务是在调用线程以外的某个线程中执行的 * 下面的执行器为每个任务生成一个新线程: * * class ThreadPerTaskExecutor implements Executor { * public void execute(Runnable r) { * new Thread(r).start(); * } * * More typically, tasks are executed in some thread other than the * caller's thread. The executor below spawns a new thread for each * task. * * <pre> {@code * class ThreadPerTaskExecutor implements Executor { * public void execute(Runnable r) { * new Thread(r).start(); * } * }}</pre> * * 许多{@code Executor}实现对任务的调度方式和时间施加某种限制 * 下面的执行器将任务的提交序列化到第二个执行器,以展示复合执行器的使用: * * class SerialExecutor implements Executor { * final Queue<Runnable> tasks = new ArrayDeque<>(); * final Executor executor; * Runnable active; * * SerialExecutor(Executor executor) { * this.executor = executor; * } * * public synchronized void execute(Runnable r) { * tasks.add(() -> { * try { * r.run(); * } finally { * scheduleNext(); * } * }); * if (active == null) { * scheduleNext(); * } * } * * protected synchronized void scheduleNext() { * if ((active = tasks.poll()) != null) { * executor.execute(active); * } * } * } * * Many {@code Executor} implementations impose some sort of * limitation on how and when tasks are scheduled. The executor below * serializes the submission of tasks to a second executor, * illustrating a composite executor. * * <pre> {@code * class SerialExecutor implements Executor { * final Queue<Runnable> tasks = new ArrayDeque<>(); * final Executor executor; * Runnable active; * * SerialExecutor(Executor executor) { * this.executor = executor; * } * * public synchronized void execute(Runnable r) { * tasks.add(() -> { * try { * r.run(); * } finally { * scheduleNext(); * } * }); * if (active == null) { * scheduleNext(); * } * } * * protected synchronized void scheduleNext() { * if ((active = tasks.poll()) != null) { * executor.execute(active); * } * } * }}</pre> * * 此包中提供的{@code Executor}实现了{@link ExecutorService},这是一个更广泛的接口 * 而{@link ThreadPoolExecutor}类提供了一个可扩展的线程池实现 * {@link Executors}类为这些执行器提供了方便的工厂方法 * * The {@code Executor} implementations provided in this package * implement {@link ExecutorService}, which is a more extensive * interface. The {@link ThreadPoolExecutor} class provides an * extensible thread pool implementation. The {@link Executors} class * provides convenient factory methods for these Executors. * * 内存一致性影响: * 先前提交给Executor中的对象,线程中操作的执行可能是在另一个线程中 * (此处想说的可能是不要忽略了内存一致性问题, 即一个对象可能在两个线程中同时访问?) * * <p>Memory consistency effects: Actions in a thread prior to * submitting a {@code Runnable} object to an {@code Executor} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * its execution begins, perhaps in another thread. * * @since 1.5 * @author Doug Lea */ publicinterfaceExecutor {
/** * 在将来的某个时间执行给定的任务 * 该任务可以在新线程、线程池或调用线程中执行,具体由{@code 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. * * @param command 可运行的任务(继承自Runnable接口) * @throws 如果无法接受执行此任务抛出: RejectedExecutionException * @throws 如果command为空抛出: NullPointerException * * @param command the runnable task * @throws RejectedExecutionException if this task cannot be * accepted for execution * @throws NullPointerException if command is null */ voidexecute(Runnable command); }
/** * (本接口是一个)提供终止的方法的Executor * 以及可以生成Future以跟踪一个或多个异步任务的进度的方法的Executor * * 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. * * 实现了ExecutorService接口的类可以关闭,这将导致它拒绝新任务 * 它提供了两种不同的方法来关闭: * shutdown方法将允许在终止之前执行以前提交的任务; * 而shutdownNow方法将阻止等待的任务启动并尝试停止当前执行的任务 * 在终止时,(应当保证)执行者没有正在执行的任务,没有等待执行的任务,并且不能提交新任务 * 应该关闭未使用的ExecutorService,以允许回收其资源 * * <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. * * 方法submit扩展了父接口Executor通过创建并返回Future来执行Runnable * 该Future用于取消执行或等待完成 * 方法invokeAny和invokeAll使用最常用的批量执行形式,执行任务集合 * 然后等待至少一个或所有任务完成 * 类ExecutorCompletionService可用于编写这些方法的自定义变体 * * <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.) * * Executors类为此包中提供的执行器服务提供工厂方法 * * <p>The {@link Executors} class provides factory methods for the * executor services provided in this package. * * 使用例子 * * <h3>Usage Examples</h3> * * 下面是一个网络服务的草图,其中线程池中的线程服务接收请求 * 它使用预配置的Executors.newFixedThreadPool工厂方法: * * 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: * * <pre> {@code * // 网络业务Server类 * class NetworkService implements Runnable { * private final ServerSocket serverSocket; * private final ExecutorService pool; * * // 初始化Server * 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> * * 以下方法分两个阶段关闭ExecutorService: * 首先通过调用shutdown拒绝传入任务,然后在必要时调用shutdownNow取消任何延迟的任务 * * <pre> {@code * void shutdownAndAwaitTermination(ExecutorService pool) { * pool.shutdown(); // 停止新任务的加入 * try { * // 等待当前任务的结束 * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { * pool.shutdownNow(); // 撤销当前执行中的任务 * // 等待任务响应被取消 * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) * System.err.println("Pool did not terminate"); * } * } catch (InterruptedException ie) { * // 如果当前线程也被中断,则(重新-)取消 * pool.shutdownNow(); * // Preserve interrupt status * Thread.currentThread().interrupt(); * } * }}</pre> * @since 1.5 * @author Doug Lea */ publicinterfaceExecutorServiceextendsExecutor {
/** * 启动有序关闭,在该关闭中: 继续执行以前提交的任务,但不接受新任务 * 如果已关闭,则调用没有其他效果 * * 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. * * 此方法不等待以前提交的任务完成执行 * 使用awaitTermination方法执行此操作 * * <p>This method does not wait for previously submitted tasks to * complete execution. Use {@link #awaitTermination awaitTermination} * to do that. * * 如果安全管理器存在并且关闭此执行器服务可能会操作调用方不允许修改的线程 * (因为它不持有java.lang.RuntimePermission) * 或者安全管理器的{@code checkAccess}方法拒绝访问 * 将会抛出SecurityException * * @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. */ voidshutdown();
/** * 尝试停止所有正在执行的任务,停止处理等待的任务,并返回等待执行的任务列表 * * Attempts to stop all actively executing tasks, halts the * processing of waiting tasks, and returns a list of the tasks * that were awaiting execution. * * 此方法不等待以前提交的任务完成执行 * 使用awaitTermination方法执行此操作 * * <p>This method does not wait for actively executing tasks to * terminate. Use {@link #awaitTermination awaitTermination} to * do that. * * 除了尽最大努力尝试停止处理正在积极执行的任务之外,没有任何保证 * 例如,典型的实现将通过Thread#interrupt取消 * 因此任何未能响应中断的任务都可能永远不会终止 * * <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. * * @return 从未开始执行的任务列表 * @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();
/** * 如果此执行器已关闭,则返回true * * @return {@code true} if this executor has been shut down */ booleanisShutdown();
/** * 如果关闭后所有任务都已完成,则返回true * 注意isTerminated永远不是true,除非首先调用shutdownshutdownNow方法 * * 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 */ booleanisTerminated();
/** * 阻塞,直到所有任务在关闭请求后完成执行 * 或发生超时,或当前线程中断(以先发生者为准) * * 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 最长等待时间 * @param unit timeout参数的时间单位 * @return {@code true}如果此执行器终止,{@code false}如果在终止之前超时 * @throws InterruptedException if interrupted while waiting */ booleanawaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
/** * 提交一个有返回值的任务以供执行,并返回表示该任务的执行结果的Future类 * Future的{@code get}方法将在任务成功完成后返回任务的结果(否则阻塞) * * 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. * * 如果要立即阻止等待任务 * 可以使用result = exec.submit(aCallable.get())格式的构造方法 * * If you would like to immediately block waiting * for a task, you can use constructions of the form * {@code result = exec.submit(aCallable).get();} * * 注意:Executors类包含一组方法 * 这些方法可以将其他一些类似于闭包的对象 * (例如java.security.PrivilegedAction)转换为Callable表单,以便提交它们 * * <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. * * @param task 要提交的任务 * @param <T> 任务结果的类型 * @return 代表任务即将完成的Future类 * @throws 如果无法计划执行任务,遭到拒绝抛出RejectedExecutionException * @throws NullPointerException if the task is null */ <T> Future<T> submit(Callable<T> task);
/** * 提交可运行的任务以供执行,并返回表示该任务的Future类 * Future的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. * * @param task the task to submit * @param result 要返回的结果 * @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);
/** * 提交可运行的任务以供执行,并返回表示该任务结果的Future类 * Future的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. * * @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 */ Future<?> submit(Runnable task);
/** * 执行给定的任务,在所有任务完成时返回一个保存其状态和结果的Future列表 * Future.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. * * @param tasks 任务的集合 * @param <T> 从任务返回的值的类型 * @return 表示任务的Future列表,其顺序与迭代器为给定任务列表生成的顺序相同,每个任务列表都已完成 * @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 * 请注意,已完成的任务可以正常终止,也可以引发异常 * 如果在执行此操作时修改了给定集合,则此方法的结果未定义 * * 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. * * @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 代表任务的Future列表,其顺序与迭代器为给定任务列表生成的顺序相同 * 如果操作没有超时,则每个任务都将完成 * 如果它超时了,其中一些任务将不会完成 * @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;
/** * 执行给定的任务,返回已成功完成的任务(即不引发异常的结果)[如果有] * 在正常或异常返回时,未完成的任务将被取消 * 如果在执行此操作时修改了给定集合,则此方法的结果未知 * * 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} * @throws IllegalArgumentException if tasks is empty * @throws ExecutionException if no task successfully completes * @throws RejectedExecutionException if tasks cannot be scheduled * for execution */ <T> TinvokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;
/** * 执行给定的任务 * 如果在给定的超时时间之前执行了某个任务,则返回已成功完成的任务的结果(不引发异常) * 在正常或异常返回时,未完成的任务将被取消 * 如果在执行此操作时修改了给定集合,则此方法的结果未知 * * 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 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> TinvokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
/** * 提供ExecutorService执行方法的默认实现 * 此类使用newTaskFor返回的RunnableFuture实现了submit, invokeAny和invokeAll}方法 * 该方法默认为此包中提供的FutureTask * 例如,submit(Runnable)的实现创建了一个关联的RunnableFuture它被执行并返回 * 子类可以重写newTaskFor方法以返回RunnableFuture实现,而不是FutureTask * * Provides default implementations of {@link ExecutorService} * execution methods. This class implements the {@code submit}, * {@code invokeAny} and {@code invokeAll} methods using a * {@link RunnableFuture} returned by {@code newTaskFor}, which defaults * to the {@link FutureTask} class provided in this package. For example, * the implementation of {@code submit(Runnable)} creates an * associated {@code RunnableFuture} that is executed and * returned. Subclasses may override the {@code newTaskFor} methods * to return {@code RunnableFuture} implementations other than * {@code FutureTask}. * * 扩展示例 * 下面是自定义ThreadPoolExecutor * 使用了CustomTask类而不是默认FutureTask类 * * <p><b>Extension example</b>. Here is a sketch of a class * that customizes {@link ThreadPoolExecutor} to use * a {@code CustomTask} class instead of the default {@code FutureTask}: * <pre> {@code * public class CustomThreadPoolExecutor extends ThreadPoolExecutor { * * static class CustomTask<V> implements RunnableFuture<V> {...} * * protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) { * return new CustomTask<V>(c); * } * protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) { * return new CustomTask<V>(r, v); * } * // ... add constructors, etc. * }}</pre> * * @since 1.5 * @author Doug Lea */ publicabstractclassAbstractExecutorServiceimplementsExecutorService {
/** * 为给定的runnable和默认值返回RunnableFuture * * Returns a {@code RunnableFuture} for the given runnable and default * value. * * @param runnable 要被包装的Runnable * @param value 返回的Future的默认值 * @param <T> the type of the given value * @return 一个RunnableFuture * 当运行时,它将运行底层runnable,作为Future * 它将产生给定的值作为其结果,并提供底层任务的取消 * @since 1.6 */ protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { returnnewFutureTask<T>(runnable, value); }
/** * 返回给定可调用任务的RunnableFuture * * @param callable the callable task being wrapped * @param <T> the type of the callable's result * @return a {@code RunnableFuture} which, when run, will call the * underlying callable and which, as a {@code Future}, will yield * the callable's result as its result and provide for * cancellation of the underlying task * @since 1.6 */ protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { returnnewFutureTask<T>(callable); }
// 含有超时的执行全部任务的方法 // 只是多了超时判断 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { if (tasks == null) thrownewNullPointerException(); finallongnanos= unit.toNanos(timeout); finallongdeadline= System.nanoTime() + nanos; ArrayList<Future<T>> futures=newArrayList<>(tasks.size()); intj=0; timedOut: try { for (Callable<T> t : tasks) futures.add(newTaskFor(t));
finalintsize= futures.size();
// Interleave time checks and calls to execute in case // executor doesn't have any/much parallelism. for (inti=0; i < size; i++) { if (((i == 0) ? nanos : deadline - System.nanoTime()) <= 0L) break timedOut; execute((Runnable)futures.get(i)); }
// 撤销ArrayList中j索引之后全部的任务 /** Cancels all futures with index at least j. */ privatestatic <T> voidcancelAll(ArrayList<Future<T>> futures, int j) { for (intsize= futures.size(); j < size; j++) futures.get(j).cancel(true); } }
//五个参数的构造函数 publicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) //六个参数的构造函数-1 publicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) //六个参数的构造函数-2 publicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) //七个参数的构造函数 publicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)