首页 > 其他 > 详细

Executor、Runnable接口

时间:2019-07-10 00:12:28      阅读:85      评论:0      收藏:0      [点我收藏+]

Executor接口

 /**
 * 执行提交的任务对象(Runnable)
 * Executor提供了一种将任务提交与任务运行方式的机制分离方法包括线程的使用、调用等细节
 */
public interface Executor {

    /**
     * 在将来的某个时间执行给定的指令
     * 指令可能运行在一个线程池的新线程中,也可能运行在调用线程中
     * @throws RejectedExecutionException 如果任务无法被接受执行
     */
    void execute(Runnable command);
}

ExecutorService接口

 /** 
 * 提供管理终止和生成Future来跟踪一个或多个一步任务的进度方法
 * 内存一致性:happen-before(先行发生)
 */
public interface ExecutorService extends Executor {

    /**
     * 启动有序关闭:之前提交的任务被执行,但不会接受新的任务
     * 如果已经关闭,额外调用没有影响
     */
    void shutdown();

    /**
     * 尝试停止所有正在执行的任务,停止处理等待的任务,并返回等待执行的任务列表
     * best-effort(尽力)尝试去终止执行中的任务,不给出任何保证,例如:典型的是通过:Thread.interrupt来实现取消,因此任务如果不响应中断可能永远不会终止
     * @return 返回未执行的任务列表
     */
    List<Runnable> shutdownNow();

    /**
     * 返回当前executor是否已经关闭
     */
    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();

    /**
     * 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
     */
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    /**
     * 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.
     *
     * <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();}
     *
     * <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);

    /**
     * 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 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);

    /**
     * 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);

    /**
     * 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 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}
     * @throws RejectedExecutionException if any task cannot be
     *         scheduled for execution
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;

    /**
     * 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 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;

    /**
     * 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> T invokeAny(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> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

 

Runnable接口

 /** 
 * 任何意在由线程执行的类都应该实现此接口
 * Runnable接口旨在为希望在活动时执行代码的对象提供通用协议,如:Thread处于活动状态表示线程已经启动且尚未停止
 * Runnable提供了active方法而非进程Thread,如果没有打算修改或增强类的基本行为,应该使用Runnable接口
 * @since   1.0
 */
@FunctionalInterface
public interface Runnable {
    /**
     * 当接口的实现被用来创建thread 实例,启动thread会使单独运行的线程执行run()方法
     */
    public abstract void run();
}

Future接口

 /** 
 * 表示异步计算的结果。提供方法以检查计算是否完成,等待其完成和检索计算结果
 *
 * 内存一致性影响:happen-before(先行发生)
 */
public interface Future<V> {

    /**
     * 尝试取消一个任务.  This attempt will
     * 如果任务:已经完成、已经被取消、或者由于其他原因无法取消 那么尝试将失败
     * 如果任务尚未启动,那么任务将不会再启动;如果任务已经启动,那么mayInterruplfRunning参数去定是否中断执此任务的线程
     * cancel()方法执行返回后,isDone()将一直返回true;isCancelled()方法返回与cancel()一致
     * {@code mayInterruptIfRunning} 执行此任务的线程是否被打断,否则允许任务执行结束
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * 返回true如果任务在正常结束前被取消
     */
    boolean isCancelled();

    /**
     * 返回true如果任务已经完成
     * 完成可能是:1:正常结束、2:异常结束、3:被取消
     */
    boolean isDone();

    /**
     * 如果需要,则等待计算结果
     * CancellationException 任务被取消
     * ExecutionException 计算出现异常
     * InterruptedException 等待计算时当前线程被中断
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * 如果需要,最多在给定时间内等待计算
     * TimeoutException 等待超时
     * 其他见get()方法
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

 

Executor、Runnable接口

原文:https://www.cnblogs.com/gsanye/p/11161115.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!