【工具类】CompletableFuture 使用详解
runAsync和supplyAsync方法,这个两个方法为CompletableFuture的主要使用方式,其主要作用给任务提供异步线程的操作方式
如何使用
CompletableFuture 提供了四个静态方法来创建一个异步操作。
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)
其中:
runAsyn方法不支持返回值
public class CompletableFutureTest02 {
public CompletableFuture Test(){
CompletableFuture future = CompletableFuture.runAsync(()->{
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(">>>>print.."+i);
}
});
return future;
}
public static void main(String[] args) {
CompletableFutureTest02 test02 = new CompletableFutureTest02();
test02.Test().join();
}
}
supplyAsync可以支持返回值
public class CompletableFutureTest {
public Integer Test() throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
});
CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(()->{
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
});
//使用get方法来获取返回值
return future.get()+future01.get();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFutureTest test = new CompletableFutureTest();
Long begin = System.currentTimeMillis();
System.out.println(">>>>>>>begin"+begin);
/*
在执行Test()方法是会启动future和future01两个线程
并且两个线程执行完毕后获取到结果值才代表Test()方法执行结束
*/
System.out.println(test.Test());
Long end = System.currentTimeMillis();
Long exec = end-begin;
System.out.println(">>>>>>>end"+end+">>>>>>exec"+exec);
}
}
计算结果完成时的回调方法
当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:
public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)
分类:
Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix