美文网首页
Executor框架(一)定义、生命周期

Executor框架(一)定义、生命周期

作者: Fakecoder_Sunis | 来源:发表于2019-02-26 14:37 被阅读0次

Executor是一个接口

Executor是一个接口,但它提供了一种标准方法将任务的提交过程执行过程解耦开来。Executor的各种实现类,还提供了对生命周期的支持,以及统计信息手机、应用程序管理机制和性能监视等。

Executor基于生产-消费者模式,提交任务的操作相当于生产者,而执行任务的线程相当于消费者。

public interface Executor {
    void execute(Runnable command);
}

Executor的生命周期

为了解决executor的生命周期问题,executor拓展了一个ExecutorService接口,添加了一些用于管理生命周期的方法。如下

public interface ExecutorService extends Executor {

    void shutdown();

    List<Runnable> shutdownNow();

    boolean isShutdown();

    boolean isTerminated();

    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    <T> Future<T> submit(Callable<T> task);

    <T> Future<T> submit(Runnable task, T result);

    Future<?> submit(Runnable task);

    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;

    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                  long timeout, TimeUnit unit)
        throws InterruptedException;
 
    <T> T invokeAny(Collection<? extends Callable<T>> tasks)
        throws InterruptedException, ExecutionException;

    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

ExecutorService的生命周期有三种状态:运行、关闭、终止

ExecutorService在初始创建时处于运行状态;

shutdown方法将执行平缓的关闭过程(不接受新的任务,同时等待已经提交的任务执行完成-同时包括那些尚未开始执行的任务);

shutdownNow方法将执行粗暴的关闭过程(尝试取消所有运行中的任务,并且不再启动队列中尚未开始执行的任务);
而当ExecutorService中的所有任务完成后,将转入终止状态。可以调用awaitTermination来等待其到达终止状态,也可以调用isTerminated来查询其是否已终止。

相关文章

网友评论

      本文标题:Executor框架(一)定义、生命周期

      本文链接:https://www.haomeiwen.com/subject/eveayqtx.html