• 批量执行异步任务CompletionService


    批量执行异步任务CompletionService

    核心思想,就是将异步结果放入到阻塞队列中,然后再消费队列,实现异步任务批量执行
    接口方法说明

    
    Future<V> submit(Callable<V> task);
    Future<V> submit(Runnable task, V result);
    Future<V> take() 
      throws InterruptedException // 阻塞式调用;
    Future<V> poll();
    Future<V> poll(long timeout, TimeUnit unit) 
      throws InterruptedException;
    
    public static void test() throws InterruptedException, ExecutionException {
            ExecutorService executor = Executors.newFixedThreadPool(3);
            CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(executor);
            cs.submit(() -> getPriceByS1());
            cs.submit(() -> getPriceByS2());
            cs.submit(() -> getPriceByS3());
            for (int i = 0; i < 3; i++) {
                Integer r = cs.take().get();
                executor.execute( () -> System.out.println("save:" + r));
            }
    }
    
    public static Integer getPriceByS1(){
            return 1;
    }
    public static Integer getPriceByS2(){
            return 2;
    }
    public static Integer getPriceByS3(){
            return 3;
    }
    
    原创:做时间的朋友
  • 相关阅读:
    (copy) Shell Script to Check Linux System Health
    HTML5 笔记1
    成年后更想要人懂
    端午不过节
    兜兜转转还是往前了一小步
    五月下旬这些天
    立陶宛话剧观后感
    杯子
    你学过的东西总会在某个时候用到
    初识理财记
  • 原文地址:https://www.cnblogs.com/PythonOrg/p/14412822.html
Copyright © 2020-2023  润新知