欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ExecutorService | Executor框架 博客分类: 线程 ExecutorServiceExecutorjuc并发线程池 

程序员文章站 2024-03-24 20:51:10
...

Excutor框架结构图:


ExecutorService | Executor框架
            
    
    博客分类: 线程 ExecutorServiceExecutorjuc并发线程池 
 

上一篇讲了Executor接口,本篇来讲一下ExecutorService接口,从图中可以看出ExecutorService扩展了Executor接口,一般扩展后,都会新增一些功能方法,它有哪些新方法呢?

 

 

一:关于ExecutorService的源码

package java.util.concurrent;
import java.util.List;
import java.util.Collection;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;

publicinterface ExecutorService extends Executor {

   /**
     * 启动一次顺序关闭,执行以前提交的任务,但不接受新任务。如果已经关闭,则调用没有其他作用。      
     */
    void shutdown();

    /**
     * 试图停止所有正在执行的活动任务,暂停处理正在等待的任务,并返回等待执行的任务列表。      
     * 无法保证能够停止正在处理的活动执行任务,但是会尽力尝试。例如,通过 Thread.interrupt()
     * 来取消典型的实现,所以任何任务无法响应中断都可能永远无法终止。
     */
    List<Runnable> shutdownNow();

    /**
     * 如果此执行程序已关闭,则返回 true。
     */
    boolean isShutdown();
    
    /**
     * 如果关闭后所有任务都已完成,则返回 true。注意,除非首先调用 shutdown 或 shutdownNow
     * 否则 isTerminated 永不为 true。      
     */
    boolean isTerminated();

    /**
     * 请求关闭、发生超时或者当前线程中断,无论哪一个首先发生之后,都将导致阻塞,直到所有任务完成执行。      
     */
    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 <tt>get</tt> method will return the task's result upon
     * successful completion.
     */
    <T> Future<T> submit(Callable<T> task);

    /**
     * Submits a Runnable task for execution and returns a Future
     * representing that task. The Future's <tt>get</tt> method will
     * return the given result upon successful completion.   
     */
    <T> Future<T> submit(Runnable task, T result);
 
    /**
     * Submits a Runnable task for execution and returns a Future
     * representing that task. The Future's <tt>get</tt> method will
     * return <tt>null</tt> upon <em>successful</em> completion.
     */
    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 <tt>true</tt> 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.
     */
    <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 <tt>true</tt> 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.
     */
    <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.
     */
    <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.
     *
     */
    <T> T invokeAny(Collection<? extends Callable<T>> tasks,  long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

}
 

 

Executor提供了管理终止的方法,以及可为跟踪一个或多个异步任务执行状况而生成 Future 的方法。  

可以关闭ExecutorService,这将导致其拒绝新任务。提供两个方法来关闭 ExecutorServiceshutdown()方法在终止前允许执行以前提交的任务,而 shutdownNow() 方法阻止等待任务启动并试图停止当前正在执行的任务。在终止时,执行程序没有任务在执行,也没有任务在等待执行,并且无法提交新任务。应该关闭未使用的 ExecutorService 以允许回收其资源。

 

Executor框架新手,看了ExecutorService的源码及源码中的说明,必定仍是一头雾水!没关系,看不懂没关系,但至少应该明白的是:

  •  Executor 接口定义了最基本的 execute 方法,用于接收用户提交的任务
  •    ExecutorService接口扩展自Executor接口,并添加了一些生命周期管理的方法。例如:ExecutorService 定义了线程池终止和创建及提交 futureTask 任务支持的方法。

一个Executor的生命周期有三种状态:运行关闭终止

 

 

二:关于ExecutorService的实现

 

ExecutorService的实现类有:

 

抽象类AbstractExecutorService:

 

package java.util.concurrent;
import java.util.*;

publicabstractclass AbstractExecutorService implements ExecutorService {

    /**
     * 为给定可运行任务和默认值返回一个 RunnableFuture.
     * @since 1.6
     */
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        returnnew FutureTask<T>(runnable, value);
    }
 
    /**
     * 为给定可调用任务返回一个 RunnableFuture.
     * @since 1.6
     */
   protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        returnnew FutureTask<T>(callable);
    }

    /**
     * 提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future.
     */
    public Future<?> submit(Runnable task) {
        if (task == null) thrownew NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }

    /**
     * 提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future.
     */
    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) thrownew NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }

    /**
     *  提交一个返回值的任务用于执行,返回一个表示任务的未决结果的 Future.
     */
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) thrownew NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }
}
 

 

说明:AbstractExecutorService类有关键字 abstart修饰,则它是一个抽象类,不允许被实例化。它提供了一些执行任务(Runnable类型)的方法。

 

 

 

参考资料:

JDK API 1.6.0

http://www.iteye.com/topic/366591

http://singleant.iteye.com/blog/1423931

 

 

  • ExecutorService | Executor框架
            
    
    博客分类: 线程 ExecutorServiceExecutorjuc并发线程池 
  • 大小: 32 KB