Java 8中, 新增加了一个包含50个方法左右的类: CompletableFuture,结合了Future的优点,提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。
ExecutorService threadPool = Executors.newFixedThreadPool(4);
List<Integer> list = Arrays.asList(1, 2, 3);
for (Integer integer : list) {
CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(integer);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "异步获取结果:" + integer;
}, threadPool)
.whenCompleteAsync((res, exception) ->
System.out.println(res)
);
}
CompletableFuture.allOf(
list.stream()
.map(key ->
CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(key);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("获取所有结果:" + key);
}, threadPool))
.toArray(CompletableFuture[]::new)
);
CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(
list.stream().map(key ->
CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(key);
} catch (Exception e) {
e.printStackTrace();
}
return "获取单个结果:" + key;
}, threadPool)
).toArray(CompletableFuture[]::new)
);
System.out.println(objectCompletableFuture.join());
Integer join = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
}, threadPool)
.thenApplyAsync(result -> {
try {
TimeUnit.SECONDS.sleep(result);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 2;
}, threadPool)
.join();
System.out.println(join);