// 导包已设置idea自动导包,如未设置需手动导入
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* 并发编程之 Future 与 CompletableFuture 学习记录,
* 参考了
*(https://blog.csdn.net/qq_28908085/article/details/108267347)
* 和
* https://www.liaoxuefeng.com/wiki/1252599548343744/1306581182447650
*/
public class TestFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// // 异步获取线程返回值,测试Future
// ExecutorService es = Executors.newCachedThreadPool();
// Callable<String> task = new StringTask();
// Future<String> future = es.submit(task);
// System.out.println(future.get());
// // 创建一个线程安全的CompletableFuture是否正常返回值的标志
// AtomicReference<Double> _result = new AtomicReference<>((double) 0);
// 创建异步执行任务
CompletableFuture<Double> cf = CompletableFuture.supplyAsync(TestFuture::fetchPrice);
// 等cf结束后再结束主线程
cf.join();
// 执行结束,无关是否执行成功
cf.thenRun(() -> System.out.println("fetchPrice End!"));
// 如果执行成功,消费处理结果
cf.thenAccept((result) -> {
// _result.set(result); // 成功获取返回值后更改标志
System.out.println("price: " + result);
});
// // 粗暴方法,主线程循环等待CompletableFuture正常返回值
// while (_result.get()==0){
// Thread.sleep(5000);
// }
// 如果执行失败
cf.exceptionally((e) -> {
System.out.println("出错了!");
e.printStackTrace();
return null;
});
// 主线程不要立刻结束,否则CompletableFuture默认使用的线程池会立刻关闭,因为主线程不会等待结果
// Thread.sleep(4000);
System.out.println("Main Thread End!");
}
static Double fetchPrice() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println();
}
// // 模拟执行异常
// if (Math.random() < 0.3) {
// throw new RuntimeException("fetch price failed!");
// }
return 5 + Math.random() * 20;
}
}
// 测试Future的工具任务类
// class StringTask implements Callable<String> {
//
// public String call() throws InterruptedException {
// Thread.sleep(10000);
// return "test callable";
// }
// }
并发编程之 Future 与 CompletableFuture 学习记录
最新推荐文章于 2024-05-11 19:00:49 发布