【Java SE】获取先完成的线程结果ExecutorCompletionService
多个线程同时执行时,每个线程所需执行时间长短不一,优先处理已经完成的任务,而不是傻傻的等待第一个线程任务完成
Callable<String> c1 = () -> { TimeUnit.SECONDS.sleep(10); return "call 10s"; }; Callable<String> c2 = () -> { TimeUnit.SECONDS.sleep(6); return "call 6s"; }; Callable<String> c3 = () -> { TimeUnit.SECONDS.sleep(2); return "call 2s"; }; List<Callable<String>> taskList = new ArrayList<>(); taskList.add(c1); taskList.add(c2); taskList.add(c3); ExecutorService executorService = Executors.newFixedThreadPool(20); ExecutorCompletionService<String> executorCompletionService = new ExecutorCompletionService<>(executorService); for (Callable task : taskList) { // 提交任务 executorCompletionService.submit(task); } for (Callable task : taskList) { // 获取结果 System.out.println(executorCompletionService.take().get()); } executorService.shutdownNow();// 该池取消尚未开始的所有任务,并试图中断正在运行的任务。executorService.shutdown(); 启动该池的关闭序列,关闭该池的执行器不在接受新的任务,当所有的任务完成后,线程池中的任务死亡 System.out.println("Exit.");