并发编程之 Future 与 CompletableFuture 学习记录

// 导包已设置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";
//     }
// }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不谷尉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值