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());
}
}
此博客只是为了记忆相关知识点,大部分为网络上的文章,在此向各个文章的作者表示感谢!