CompletableFuture的用法及简要原理

本文详细介绍了Java的CompletableFuture的用法,包括thenRun、thenAccept、thenApply、whenComplete、thenCombine、thenCompose、allof、anyof等方法,并探讨了其内部原理,特别是如何利用线程池执行任务并在完成后设置结果或异常。此外,还讲解了Future.get方法的工作机制,即在等待任务完成时如何利用AQS实现线程同步。
摘要由CSDN通过智能技术生成
//自定义线程池
private static ThreadPoolExecutor executor = new ThreadPoolExecutor(8,16,20, TimeUnit.SECONDS,new LinkedBlockingDeque<>(20), Executors.defaultThreadFactory(), (r, executor1) -> new Thread(r).start());
 System.out.println("Main 线程名称: "+Thread.currentThread().getName());

//runAsync 开启一个异步任务,接受一个Runnable,可选传入自定义线程池
CompletableFuture.runAsync(()-> System.out.println(Thread.currentThread().getName()+"     CSDN——Mutou_ren  CompletableFuture.runAsync"),executor);
//supplyAsync 开启一个异步任务,接受一个supplier函数,如果不指定自定义线程池默认都是使用ForkJoinPool.commonPool线程池
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()-> (Thread.currentThread().getName()+"     CSDN——Mutou_ren  CompletableFuture.supplyAsync"));
System.out.println(Thread.currentThread().getName()+"   "+future1.get());

在这里插入图片描述

thenRun

//thenRun接受一个runnable ,无法读取前面的结果
 CompletableFuture.supplyAsync(()->{
   
            System.out.println("thenRun前置准备睡眠");
            try {
   
                Thread.sleep(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值