目录
代码
package test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureTest {
private static ExecutorService executorService = Executors.newFixedThreadPool(8);
public static void main(String[] args) throws InterruptedException {
// 创建异步执行任务:
CompletableFuture<Double> completedFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("start");
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
if (Math.random() < 0.3) {
throw new RuntimeException("fetch price failed!");
}
return 5 + Math.random() * 20;
}, executorService);
// 如果执行成功:
completedFuture.thenAccept((result) -> {
System.out.println("price: " + result);
});
// 如果执行异常:
completedFuture.exceptionally((e) -> {
e.printStackTrace();
return null;
});
Thread.currentThread().join();
}
}