Java future 异步返回超时处理
资料
Java多线程 CompletableFuture详解: https://www.cnblogs.com/myhomepages/p/16516737.html
Java future 异步返回超时处理
package org.example;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println("执行有返回值的异步任务");
try {
for (int i = 0; i < 5; i++) {
System.out.println(i);
TimeUnit.SECONDS.sleep(1);
}
// TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "Hello World";
});
try {
System.out.println("等待10s返回:" + future.get(6, TimeUnit.SECONDS));
} catch (Exception ex) {
System.out.println("等待10s返回异常");
}
if (future.isDone()) {
System.out.println("返回成功:" + future.isDone());
} else {
System.out.println("返回异常:" + future.isDone());
}
// System.out.println("立即返回:" + future.get());
}
}
此博客主要用于记录相关知识点,大部分内容来自网络文章,特此感谢各位作者