批量执行异步任务CompletionService

时间:2023-03-09 06:17:40
批量执行异步任务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;
}

相关文章