需求:需要异步执行多个任务,获取每个任务的结果。根据任务结果判断是否继续后面的操作
public static void main(String[] args) {
List<CompletableFuture> objects = Collections.synchronizedList(new ArrayList<>());
ExecutorService es = Executors.newFixedThreadPool(3);
objects.add(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "任务1";
}, es)
.handle((result,e)->{
System.out.println("结果和异常信息"+result+"-error:"+e);
return result;
}));
objects.add(CompletableFuture.supplyAsync(() -> {
return "任务2";
}));
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(objects.toArray(new CompletableFuture[objects.size()]));
List<Object> collect = objects.stream().map(CompletableFuture::join).collect(Collectors.toList());
System.out.println("全部执行结果:"+collect);
System.out.println("是否全部完成:"+voidCompletableFuture.isDone());
es.shutdown();
}
方式二 使用Future ,示例:按循序执行,等获取到指定任务的结果后再继续执行
ExecutorService executorService = Executors.newFixedThreadPool(3);
Future<String> submit = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
return "我是任务1结果";
}
});
Future<String> submit2 = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(2500);
return "我是任务2结果";
}
});
String s = submit.get();
String s2 = submit2.get();
System.out.println("任务1:"+s);
System.out.println("任务2:"+s2);
System.out.println("执行完成");
使用CountDownLatch实现 :一个比赛的示例
CountDownLatch countDownLatch = new CountDownLatch(5);
ThreadPoolExecutor tp = new ThreadPoolExecutor(5, 5, 10, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
tp.allowCoreThreadTimeOut(true);
for (int i = 0; i < 5; i++) {
int finalI = i + 1;
Runnable runnable = new Runnable() {
@Override
public void run() {
Long ll = (long) (Math.random() * 1000);
try {
Thread.sleep(ll);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
System.out.println(finalI + "号选手,完成了比赛!:" + ll + "秒:" + Thread.currentThread().getName());
}
}
};
tp.submit(runnable);
}
System.out.println("等待5个运动员都跑完.....");
countDownLatch.await();
tp.shutdown();
System.out.println(tp.isShutdown());
System.out.println(tp.isTerminated());
System.out.println("所有人都跑完了,比赛结束。");