Java使用CompletableFuture实现异步
import java.util.concurrent.CompletableFuture;
public class Application {
public static void main(String[] args) {
CompletableFuture<String> future1 = futureCall();
CompletableFuture<String> future2 = futureCall();
try {
CompletableFuture.allOf(future1, future2).whenComplete((s, ext) -> {
try {
System.out.println(future1.get());
System.out.println(future2.get());
} catch (Exception e) {
e.printStackTrace();
}
}).get();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("done");
}
public static CompletableFuture<String> futureCall() {
return CompletableFuture.supplyAsync(() -> {
try {
System.out.println("hello");
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return "world";
});
}
} 最后更新于1年前
本文由人工编写,AI优化,转载请注明原文地址: Java使用CompletableFuture实现异步
推荐阅读
评论 (0)
发表评论
昵称:加载中...
暂无评论,快来发表第一条评论吧!