zoukankan      html  css  js  c++  java
  • 使用CompletionService结合ExecutorService批处理任务

    CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象。
    如果你向Executor提交了一个批处理任务,并且希望在它们完成后获得结果。为此你可以将每个任务的Future保存进一个集合,然后循环这个集合调用Future的get()取出数据。幸运的是CompletionService帮你做了这件事情。
    CompletionService整合了Executor和BlockingQueue的功能。你可以将Callable任务提交给它去执行,然后使用类似于队列中的take和poll方法,在结果完整可用时获得这个结果,像一个打包的Future。
    CompletionService的take返回的future是哪个先完成就先返回哪一个,而不是根据提交顺序。
    例子:
    复制代码
     1 import java.util.Random;
     2 import java.util.concurrent.Callable;
     3 import java.util.concurrent.CompletionService;
     4 import java.util.concurrent.ExecutionException;
     5 import java.util.concurrent.ExecutorCompletionService;
     6 import java.util.concurrent.ExecutorService;
     7 import java.util.concurrent.Executors;
     8  
     9 public class CallableAndFuture {
    10  
    11         public static void main(String[] args) {
    12               ExecutorService threadPool = Executors. newFixedThreadPool(10);
    13               CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool);
    14  
    15                for (int i = 0; i < 10; i++) {
    16                       final int seq = i;
    17                      System. out.println("开始提交第" + seq + "个任务");
    18                      completionService.submit( new Callable<Integer>() {
    19  
    20                             @Override
    21                             public Integer call() throws Exception {
    22                                   Thread. sleep(new Random().nextInt(5000));
    23                                    return seq;
    24                            }
    25                      });
    26               }
    27  
    28                for (int i = 0; i < 10; i++) {
    29                       try {
    30                             // 取出并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则等待。
    31                            Integer seq = completionService.take().get();
    32                            System. out.println("第" + seq + "个任务返回");
    33                      } catch (InterruptedException e) {
    34                            e.printStackTrace();
    35                      } catch (ExecutionException e) {
    36                            e.printStackTrace();
    37                      }
    38               }
    39        }
    40  
    41 }
    复制代码
  • 相关阅读:
    异常处理(throw,throws,try,catch,finally)
    内部类、匿名内部类、静态内部类
    Object,equals,toString
    有关于多态和静态绑定与动态绑定的知识
    接口的基本知识
    关于继承的基本知识,方法重写,final和abstract的使用, 动态绑定和静态绑定的知识
    设计模式: 单列设计模式 、模块方法设计模式、装饰设计模式、工厂设计模式、适配器设计模式
    zabbix设置维护周期
    zabbix入门
    yum安装zabbix 5.0 LTS
  • 原文地址:https://www.cnblogs.com/zhangyuhang3/p/6872674.html
Copyright © 2011-2022 走看看