ExecutorService

java.util.concurrent.ExecutorService

An Executor
that provides methods to manage termination and methods that can produce a Future for
tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to
reject new tasks. Two different methods are provided for shutting down an
ExecutorService. The shutdown()
method will allow previously submitted tasks to execute before terminating,
while the shutdownNow()
method prevents waiting tasks from starting and attempts to stop currently
executing tasks. Upon termination, an executor has no tasks actively executing,
no tasks awaiting execution, and no new tasks can be submitted. An unused
ExecutorService should be shut down to allow reclamation of its
resources.

Method submit extends base method Executor.execute(Runnable)
by creating and returning a Future that
can be used to cancel execution and/or wait for completion. Methods
invokeAny and invokeAll perform the most commonly
useful forms of bulk execution, executing a collection of tasks and then waiting
for at least one, or all, to complete. (Class ExecutorCompletionService
can be used to write customized variants of these methods.)

The Executors
class provides factory methods for the executor services provided in this
package.

Usage Examples

Here is a sketch of a network service in which threads in
a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool(int)
factory method:

 
 class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;

   public NetworkService(int port, int poolSize)
       throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   }

   public void run() { // run the service
     try {
       for (;;) {
         pool.execute(new Handler(serverSocket.accept()));
       }
     } catch (IOException ex) {
       pool.shutdown();
     }
   }
 }

 class Handler implements Runnable {
   private final Socket socket;
   Handler(Socket socket) { this.socket = socket; }
   public void run() {
     // read and service request on socket
   }
 }

The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:

 
 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

Since:
1.5
时间: 2024-11-07 09:53:36

ExecutorService的相关文章

ExecutorService 的理解与使用

接口 Java.util.concurrent.ExecutorService 表述了异步执行的机制,并且可以让任务在后台执行.壹個 ExecutorService 实例因此特别像壹個线程池.事实上,在 java.util.concurrent 包中的 ExecutorService 的实现就是壹個线程池的实现. ExecutorService 样例 这里有壹個简单的使用Java 实现的 ExectorService 样例: [java] view plain copy ExecutorServ

Handler+ExecutorService(线程池)+MessageQueue模式+缓存模式

android线程池的理解,晚上在家无事 预习了一下android异步加载的例子,也学习到了一个很重要的东东 那就是线程池+缓存  下面看他们的理解. [size=1.8em]Handler+Runnable模式 我们先看一个并不是异步线程加载的例子,使用 Handler+Runnable模式. 这里为何不是新开线程的原因请参看这篇文章:Android Runnable 运行在那个线程 这里的代码其实是在UI 主线程中下载图片的,而不是新开线程. 我们运行下面代码时,会发现他其实是阻塞了整个界面

ExecutorService.invokeAny()和ExecutorService.invokeAll()的使用剖析

ExecutorService是JDK并发工具包提供的一个核心接口,相当于一个线程池,提供执行任务和管理生命周期的方法.ExecutorService接口中的大部分API都是比较容易上手使用的,本文主要介绍下invokeAll和invokeAll方法的特性和使用. package tasks; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; public class SleepSecondsC

使用CompletionService结合ExecutorService批处理任务

CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象. 如果你向Executor提交了一个批处理任务,并且希望在它们完成后获得结果.为此你可以将每个任务的Future保存进一个集合,然后循环这个集合调用Future的get()取出数据.幸运的是CompletionService帮你做了这件事情. CompletionService整合了Executor和BlockingQueue的功能.你可以将Callabl

Java ExecutorService 多线程实践(一)

需要实现一个多线程并发的业务场景,启动若干子线程,最后要所有子线程运行结束才结束.(类似 .NET 里的 Task WaitAll ) Java 中的 ExecutorService 多线程编程模型提供这样一个机制,通过代码来介绍一下. 方法一:ExecutorService#awaitTermination /** * Blocks until all tasks have completed execution after a shutdown * request, or the timeo

Java多线程系列七——ExecutorService

java.util.concurrent.ExecutorService接口提供了许多线程管理的方法 Method 说明 shutdown 拒绝接收新的任务,待已提交的任务执行后关闭,且宿主线程不阻塞,若需要阻塞可借助awaitTermination实现 shutdownNow 停止所有正在执行的任务,挂起未执行的任务并关闭,且宿主线程不阻塞,若需要阻塞可借助awaitTermination实现 awaitTermination 当发生shutdown时,阻塞宿主线程直到约定的时间已过或者所有任

Java并发编程 - Executor,Executors,ExecutorService, CompletionServie,Future,Callable

一.Exectuor框架简介 Java从1.5版本开始,为简化多线程并发编程,引入全新的并发编程包:java.util.concurrent及其并发编程框架(Executor框架). Executor框架是指java 5中引入的一系列并发库中与executor相关的一些功能类,其中包括线程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等.他们的关系为 在Executor框架中,使用执行器(Exectuo

Java基础之-ExecutorService

翻译javadoc系列文章之:ExecutorService /** * An {@link Executor} that provides methods to manage termination and * methods that can produce a {@link Future} for tracking progress of * one or more asynchronous tasks. * * <p> An <tt>ExecutorService</

Java再学习——Executor,ExecutorService,ScheduledExecutorService与Executors

1,Executor.ExecutorService和ScheduledExecutorService,它们都是接口,它们的关系是ScheduledExecutorService继承ExecutorService而ExecutorService 又继承Executor. 这些只要点开源码就能看得到. 2,对于Executor接口,它只有一个方法void execute(Runnable command);而其后的ExecutorService和ScheduledExecutorService就各

Android学习笔记之ExecutorService线程池的应用....

PS:转眼间就开学了...都不知道这个假期到底是怎么过去的.... 学习内容: ExecutorService线程池的应用... 1.如何创建线程池... 2.调用线程池的方法,获取线程执行完毕后的结果... 3.关闭线程...   首先我们先了解一下到底什么是线程池,只有了解了其中的道理,我们才能够进行应用...java.util.concurrent.ExecutorService表述了异步执行的机制   首先我们简单的举一个例子... package executor; import ja