【J.U.C】线程池之几个常用接口介绍

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】

文章首发于:clawhub.club


Executor

执行提交的Runnable任务。

    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);
    }

ExecutorService

一个{@link Executor},提供管理终止的方法,以及可以生成一个{@link Future}的方法,用于跟踪一个或多个异步任务的进度。
继承了Executor接口,这里之贴出几个常用方法:

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.
         */
        void shutdown();
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.
         * 除了尽最大努力停止处理积极执行的任务外,没有任何保证。
         * 例如,典型的实现将通过{@link Thread#interrupt}取消,
         * 因此任何未能响应中断的任务都可能永远不会终止。
         *
         * @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.
         */
        List<Runnable> shutdownNow();
isShutdown()
        /**
         * Returns {@code true} if this executor has been shut down.
         *
         * @return {@code true} if this executor has been shut down
         */
        boolean isShutdown();
isTerminated()
        /**
         * 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.
         * 如果关闭后所有任务都已完成,则返回{@code true}。
         * 注意,除非首先调用了{@code shutdown}或{@code shutdownNow},
         * 否则{@code isTerminated}永远不会是{@code true}。
         *
         * @return {@code true} if all tasks have completed following shut down
         */
        boolean isTerminated();
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.
         * 提交一个value-returning任务以执行,并返回一个表示该任务未决结果的Future。
         * Future的{@code 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();}
         * 如果希望立即阻塞等待任务,可以使用如下的结构
         * {@code 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.
         *
         * @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);
awaitTermination(long timeout, TimeUnit unit)
        /**
         * Blocks until all tasks have completed execution after a shutdown
         * request, or the timeout occurs, or the current thread is
         * interrupted, whichever happens first.
         * 阻塞,直到所有任务都在shutdown请求之后执行完毕,
         * 或者超时发生,或者当前线程被中断(以先发生的情况为准)。
         *
         * @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
         */
        boolean awaitTermination(long timeout, TimeUnit unit)
            throws InterruptedException;

ScheduledExecutorService

一个{@link ExecutorService},它可以安排命令在给定的延迟之后运行,或者定期执行。
继承自ExecutorService接口由一下四个方法组成:

schedule(Runnable command, long delay, TimeUnit unit)
     /**
         * Creates and executes a one-shot action that becomes enabled
         * after the given delay.
         * 创建并执行在给定延迟之后启用的一次性操作。
         *
         * @param command the task to execute
         * @param delay   the time from now to delay execution
         * @param unit    the time unit of the delay parameter
         * @return a ScheduledFuture representing pending completion of
         * the task and whose {@code get()} method will return
         * {@code null} upon completion
         * @throws RejectedExecutionException if the task cannot be
         *                                    scheduled for execution
         * @throws NullPointerException       if command is null
         */
        public ScheduledFuture<?> schedule(Runnable command,
                                           long delay, TimeUnit unit);
schedule(Callable callable,long delay, TimeUnit unit)
     /**
         * Creates and executes a ScheduledFuture that becomes enabled after the
         * given delay.
         * 创建并执行在给定延迟之后启用的ScheduledFuture。
         *
         * @param callable the function to execute
         * @param delay    the time from now to delay execution
         * @param unit     the time unit of the delay parameter
         * @param <V>      the type of the callable's result
         * @return a ScheduledFuture that can be used to extract result or cancel
         * @throws RejectedExecutionException if the task cannot be
         *                                    scheduled for execution
         * @throws NullPointerException       if callable is null
         */
        public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                               long delay, TimeUnit unit);
scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)
      /**
         * Creates and executes a periodic action that becomes enabled first
         * after the given initial delay, and subsequently with the given
         * period;
         * <p>
         * 创建并执行一个周期性操作,该操作在给定的初始延迟之后首先启用,然后在给定的周期内启用;
         * that is executions will commence after
         * {@code initialDelay} then {@code initialDelay+period}, then
         * {@code initialDelay + 2 * period}, and so on.
         * If any execution of the task
         * encounters an exception, subsequent executions are suppressed.
         * 如果任务的任何执行遇到异常,则禁止后续执行。
         * <p>
         * Otherwise, the task will only terminate via cancellation or
         * termination of the executor.
         * 否则,任务只会通过执行器的取消或终止而终止。
         * <p>
         * If any execution of this task
         * takes longer than its period, then subsequent executions
         * may start late, but will not concurrently execute.
         * 如果此任务的任何执行时间超过其周期,则后续执行可能会延迟开始,但不会并发执行。
         *
         * @param command      the task to execute
         * @param initialDelay the time to delay first execution
         * @param period       the period between successive executions
         * @param unit         the time unit of the initialDelay and period parameters
         * @return a ScheduledFuture representing pending completion of
         * the task, and whose {@code get()} method will throw an
         * exception upon cancellation
         * @throws RejectedExecutionException if the task cannot be
         *                                    scheduled for execution
         * @throws NullPointerException       if command is null
         * @throws IllegalArgumentException   if period less than or equal to zero
         */
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                      long initialDelay,
                                                      long period,
                                                      TimeUnit unit);
scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit)
    /**
         * Creates and executes a periodic action that becomes enabled first
         * after the given initial delay, and subsequently with the
         * given delay between the termination of one execution and the
         * commencement of the next.  If any execution of the task
         * encounters an exception, subsequent executions are suppressed.
         * Otherwise, the task will only terminate via cancellation or
         * termination of the executor.
         * 创建并执行一个周期性操作,该操作在给定的初始延迟之后首先启用,然后在一次执行的终止和下一次执行的开始之间使用给定的延迟。
         * 如果任务的任何执行遇到异常,则禁止后续执行。
         * 否则,任务只会通过执行器的取消或终止而终止。
         *
         * @param command      the task to execute
         * @param initialDelay the time to delay first execution
         * @param delay        the delay between the termination of one
         *                     execution and the commencement of the next
         * @param unit         the time unit of the initialDelay and delay parameters
         * @return a ScheduledFuture representing pending completion of
         * the task, and whose {@code get()} method will throw an
         * exception upon cancellation
         * @throws RejectedExecutionException if the task cannot be
         *                                    scheduled for execution
         * @throws NullPointerException       if command is null
         * @throws IllegalArgumentException   if delay less than or equal to zero
         */
        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                         long initialDelay,
                                                         long delay,
                                                         TimeUnit unit);

ThreadFactory

按需创建新线程的对象。
···java
public interface ThreadFactory {

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @param r a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     *         create a thread is rejected
     */
    Thread newThread(Runnable r);

}

···

Callable

返回任务结果也可能抛出异常。

    @FunctionalInterface
    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;
    }

Future

{@code Future}表示异步计算的结果。方法用于检查计算是否完成,等待计算完成并检索计算结果。
只有当计算完成时,才可以使用方法{@code get}检索结果,如果需要,可以阻塞,直到准备好为止。
取消由{@code cancel}方法执行。还提供了其他方法来确定任务是否正常完成或被取消。一旦计算完成,就不能取消计算。

    public interface Future<V> {

        /**
         * Attempts to cancel execution of this task.  This attempt will
         * fail if the task has already completed, has already been cancelled,
         * or could not be cancelled for some other reason. If successful,
         * and this task has not started when {@code cancel} is called,
         * this task should never run.  If the task has already started,
         * then the {@code mayInterruptIfRunning} parameter determines
         * whether the thread executing this task should be interrupted in
         * an attempt to stop the task.
         *
         * <p>After this method returns, subsequent calls to {@link #isDone} will
         * always return {@code true}.  Subsequent calls to {@link #isCancelled}
         * will always return {@code true} if this method returned {@code true}.
         *
         * @param mayInterruptIfRunning {@code true} if the thread executing this
         * task should be interrupted; otherwise, in-progress tasks are allowed
         * to complete
         * @return {@code false} if the task could not be cancelled,
         * typically because it has already completed normally;
         * {@code true} otherwise
         */
        boolean cancel(boolean mayInterruptIfRunning);

        /**
         * Returns {@code true} if this task was cancelled before it completed
         * normally.
         *
         * @return {@code true} if this task was cancelled before it completed
         */
        boolean isCancelled();

        /**
         * Returns {@code true} if this task completed.
         *
         * Completion may be due to normal termination, an exception, or
         * cancellation -- in all of these cases, this method will return
         * {@code true}.
         *
         * @return {@code true} if this task completed
         */
        boolean isDone();

        /**
         * Waits if necessary for the computation to complete, and then
         * retrieves its result.
         *
         * @return the computed result
         * @throws CancellationException if the computation was cancelled
         * @throws ExecutionException if the computation threw an
         * exception
         * @throws InterruptedException if the current thread was interrupted
         * while waiting
         */
        V get() throws InterruptedException, ExecutionException;

        /**
         * Waits if necessary for at most the given time for the computation
         * to complete, and then retrieves its result, if available.
         *
         * @param timeout the maximum time to wait
         * @param unit the time unit of the timeout argument
         * @return the computed result
         * @throws CancellationException if the computation was cancelled
         * @throws ExecutionException if the computation threw an
         * exception
         * @throws InterruptedException if the current thread was interrupted
         * while waiting
         * @throws TimeoutException if the wait timed out
         */
        V get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException;

Delayed

一种混合风格的接口,用于标记在给定延迟之后应该执行的对象。

    public interface Delayed extends Comparable<Delayed> {

        /**
         * Returns the remaining delay associated with this object, in the
         * given time unit.
         * 在给定的时间单位中返回与此对象关联的剩余延迟。
         *
         * @param unit the time unit
         * @return the remaining delay; zero or negative values indicate
         * that the delay has already elapsed
         */
        long getDelay(TimeUnit unit);
    }

ScheduledFuture

    /**
     * A delayed result-bearing action that can be cancelled.
     * Usually a scheduled future is the result of scheduling
     * a task with a {@link ScheduledExecutorService}.
     *
     * @since 1.5
     * @author Doug Lea
     * @param <V> The result type returned by this Future
     */
    public interface ScheduledFuture<V> extends Delayed, Future<V> {
    }

来源:https://www.jianshu.com/p/347ea7f881f8

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » 【J.U.C】线程池之几个常用接口介绍

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏