ExecutorService

定义

DOC:

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 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.)

翻译:

  1. 首先他是一个执行器(Executor),增强版的执行器:可以管理执行器的关闭。可以将异步任务包装成Future任务(跟踪任务的状态)
  1. 一个ExecutorService 可以被关闭,这样新的任务来了将会拒绝新的任务。方法为:shutdown(新的任务不执行,老的任务将等待其执行完成),shutdownNow(新任务不执行,老任务尝试关闭)。
  2. 其中的 submit方法基于 execute方法。他将会生成一个Future任务(可以被cancel和等待执行完成)

官方例子

网络任务的多线程处理:

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
   }
 }}

如下是关闭 ExecutorService的两个步骤:

  1. 拒绝新来的任务,等待老的任务去执行完毕。
  2. 调用shutdownNow gg思密达
 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();
   }
 }}

直接子类 AbstractExecutorService

提供newTaskFor()方法,将runable,callable包装成RunnableFuture

结构:

由上图知:AbstractExecutorService 是对 ExcutorService的默认实现。

官方例子

 public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
  // ThreadPoolExecutor 继承自 ExecutorService

   static class CustomTask  implements RunnableFuture  {...

   protected   RunnableFuture  newTaskFor(Callable  c) {
       return new CustomTask (c);
   }
   protected   RunnableFuture  newTaskFor(Runnable r, V v) {
       return new CustomTask (r, v);
   }
   // ... add constructors, etc.
 }}

代码实现:

将runnable和callable包装成RunnableFuture


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 时间匆匆流过,我已经毕业两年了。突然发现奥运冠军比自己小了好几岁,自己的同龄人已经达到了自己永远不可能的高度。 也...
    xiaojinwu阅读 218评论 0 0
  • 陈女士和她的前夫结婚才半年就离婚了。她告诉我一些关于她和她前夫的事。在他们谈恋爱的那三年里,她前夫每天都很勤快,把...
    康兰居阅读 3,848评论 9 57
  • 配合ios完成分享页的对接,以及页面的测试修改。和方硕配合实现书院流程。 期间因为appid的事出过岔子,以后对待...
    LiLiLiH阅读 211评论 0 0
  • 小时候画在手上的表没有动,却带走了我们最好的时光。 不要轻易把伤口揭开给别人看,因为别人看的是热闹,而痛的却是...
    雪茜阅读 450评论 0 0