CompletableFuture使用详解
1、 runAsync 和 supplyAsync方法
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)示例
//无返回值
public static void runAsync() throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.println("run end ...");
});
future.get();
}
//有返回值
public static void supplyAsync() throws Exception {
CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.println("run end ...");
return System.currentTimeMillis();
});
long time = future.get();
System.out.println("time = "+time);
}2、计算结果完成时的回调方法
示例
3、 thenApply 方法
示例
4、 handle 方法
示例
5、 thenAccept 消费处理结果
示例
6、thenRun 方法
示例
7、thenCombine 合并任务
示例
8、thenAcceptBoth
示例
9、applyToEither 方法
示例
10、acceptEither 方法
示例
11、runAfterEither 方法
示例
12、runAfterBoth
示例
13、thenCompose 方法
示例
参考:
最后更新于