`
周凡杨
  • 浏览: 233238 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

ExecutorService | Executor框架

阅读更多

Excutor框架结构图:



 

上一篇讲了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

 

 

  • 大小: 32 KB
0
3
分享到:
评论

相关推荐

    Executor框架使用详解

    Executor框架是Java并发编程的核心组件,它在Java 5中被引入,极大地简化了多线程编程。这个框架是基于`java.util.concurrent`包中的接口和类构建的,旨在提供线程池服务、任务调度以及并发执行任务的能力。Executor...

    掌握并发的钥匙:Java Executor框架深度解析

    # 掌握并发的钥匙:Java Executor框架深度解析 Java作为一种广泛应用的编程语言,自1995年由Sun Microsystems公司(现属Oracle公司)首次发布以来,已经发展成为软件开发领域的重要工具。Java的设计目标包括跨平台...

    Java多线程之Executor框架.docx

    Java的Executor框架是Java 1.5引入的用于管理和控制多线程的一种机制,它旨在解决直接使用`new Thread(…).start()`方法创建线程所带来的问题。在传统的多线程编程中,直接创建和销毁线程会导致大量开销,且无法有效...

    线程池之Executor框架.docx

    Java中的Executor框架是多线程编程的一个重要组成部分,它始于JDK5,目的是为了更好地管理和控制线程的执行。Executor框架的设计理念是将任务(工作单元)与执行机制分离,从而提高了程序的可扩展性和灵活性。 1. *...

    Java Executor 框架的实例详解

    Executor 框架的主要组件包括 Executor 接口、ExecutorService 接口、ThreadPoolExecutor 类、ScheduledThreadPoolExecutor 类等。 二、Executor 接口 Executor 接口是 Executor 框架的核心接口,定义了 execute()...

    java并发编程:Executor、Executors、ExecutorService.docx

    Java并发编程中的Executor、Executors和ExecutorService是Java并发编程框架的重要组成部分,它们为开发者提供了高效管理和控制线程执行的工具。以下是对这些概念的详细解释: 1. Executor: Executor是一个接口,它...

    Java并发之线程池Executor框架的深入理解

    Java并发之线程池Executor框架的深入理解 Java中的线程池Executor框架是Java并发编程中的一种常见机制,用于管理和执行异步任务。通过使用线程池,可以大大减少线程的创建和销毁开销,从而提高系统的性能和稳定性。...

    java 中Executor, ExecutorService 和 Executors 间的不同

    Java 中的 Executor, ExecutorService 和 Executors 是 Java Executor 框架的重要组件,用于提供线程池的功能。在 Java 1.5 之后,Executor 框架提供了多种内置的线程池,例如 FixedThreadPool 和 CachedThreadPool ...

    Java-Executor并发框架.docx

    Java并发框架中的Executor服务是...总之,Java的Executor并发框架是多线程编程的强大工具,理解并熟练使用ExecutorService和相关工厂类,能够帮助开发者更好地设计和优化并发程序,提高系统的并发性能和资源利用率。

    Java Executor 框架学习总结

    `Executor` 框架的另一个关键组件是 `ExecutorService`,它是 `Executor` 的子接口,提供了更多的管理和控制功能,如 `shutdown()` 用于关闭服务,`submit()` 用于提交带返回值的任务等。此外,`Future` 和 `...

    顶层接口Executors详解

    Executor框架有两个关键类实现了ExecutorService接口:ThreadPoolExecutor和ScheduledThreadPoolExecutor。 * 异步计算的结果:包括Future接口和实现Future接口的FutureTask类,代表异步计算的结果。 4. Executor...

    第20章 Part5 并发工具执行器与线程池.pdf

    在Java 5引入的Executor框架的基础上,Executors类提供了一些便捷的工厂方法,用于创建不同类型的ExecutorService实例。例如,Executors.newFixedThreadPool(int nThreads)方法创建了一个固定数量的线程池,...

    Android Executor线程池

    在`Executor`框架中,`ExecutorService`是核心接口,它扩展了`Executor`接口并添加了一些用于管理和控制线程池的方法,如提交任务、关闭线程池等。Android开发者通常会使用`ThreadPoolExecutor`或`...

    并发编程之Executor线程池原理与源码解读.pdf

    本文将详细解读Java中Executor框架的线程池原理和源码,同时探讨线程池的调优和监控方法。 首先,线程池的主要作用包括:避免了线程的无限制创建,减少了线程创建和销毁的开销,提升系统性能;实现任务的快速响应,...

    Java并发框架:Executor API详解

    Executor框架通过将任务的创建与执行分离开,使得开发者可以专注于任务的逻辑,而无需关心线程的创建、管理和销毁等细节。 1. **Executor框架的核心概念** - **Executor**: 它是一个接口,定义了执行任务的基本...

    03 多线程开发如此简单—Java中如何编写多线程程序.pdf

    Executor框架是Java并发编程的强大工具,它提供了线程池服务,能够有效地管理和控制线程,避免频繁创建和销毁线程带来的开销。ExecutorService是Executor接口的实现,可以使用`Executors`类创建各种类型的线程池。 ...

    Java线程创建的四种方式

    以上四种方式中,继承Thread或实现Runnable适合简单的线程创建,而Executor框架和Callable接口适用于更复杂的并发控制和结果处理。在实际开发中,我们通常会根据需求选择最适合的线程创建方法。对于大型项目,推荐...

    Java多线程实现的四种方式

    Java 5引入了Executor框架,它提供了一种更加灵活和强大的线程管理机制。ExecutorService可以创建、管理和控制线程池,避免了频繁创建和销毁线程的开销。通过ThreadPoolExecutor或Executors类可以创建...

    Java并发的四种风味ThreadExecutorFork

    接下来是Executor框架,它是Java并发编程的一个重要里程碑。`java.util.concurrent.Executor`接口提供了一种更抽象的方式来管理线程,允许开发者专注于任务的提交,而无需直接处理线程的创建和销毁。ExecutorService...

    java经典多线程示例

    ExecutorService是Executor框架的核心接口,它可以创建并管理线程池。通过ThreadPoolExecutor可以创建一个线程池,然后使用submit()或execute()方法提交Runnable或Callable任务。 4. 同步机制: - synchronized...

Global site tag (gtag.js) - Google Analytics