CompletableFuture异步编程

文章讨论了Java中Future的缺点,如同步阻塞和缺乏回调机制。然后介绍了CompletableFuture的优势,它提供了丰富的回调函数和异步任务组合方式,包括runAsync、supplyAsync以及then系列方法,用于更灵活地处理异步任务和异常。此外,还展示了如何使用thenCompose和thenCombine进行异步任务的编排。

1.普通Future的缺点

不知道任务什么时候完成, 获取任务结果时必须要get,如果get不到就会同步阻塞, 没有函数回调

问:什么是同步,什么是异步

需要等待结果返回,才能运行是同步

不需要等待结果返回,就能运行是异步

函数回调: 任务完成后会通知调用它的线程

public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        //读取敏感词汇
        Future<String[]> filterWordsFuture = executor.submit(() -> {
            String str = CommonUtils.readFile("filter_words.txt");
            return str.split(",");
        });
        //读新闻稿
        Future<String> newsFuture = executor.submit(() -> {
            return CommonUtils.readFile("news.txt");
        });
        //替换操作
        Future<String> replaceFuture = executor.submit(() -> {
            String[] words = filterWordsFuture.get();
            String news = newsFuture.get();
            for (String word : words) {
                news = news.replaceAll(word, "*");
            }
            return news;
        });

        //打印替换后的结果

        String news = replaceFuture.get();
        System.out.println(news);

    }
}

2.CompletableFuture的优势

  • 提供各种场景的回调函数
  • 可以组合多个Future
  • 提供全方面的异常处理
  • 无缝衔接lambda表达式和Stream API

3.创建异步任务

1.runAsync

开启一个无返回值的异步任务

public class RunAsyncDemo {
    public static void main(String[] args) {
        CommonUtils.printTheadLog("主线程 start");
        CompletableFuture.runAsync(() -> {
            CommonUtils.printTheadLog("读取文件,异步任务开始");
            CommonUtils.sleepSecond(3);
            CommonUtils.printTheadLog("读取文件,异步任务结束");
        });
        CommonUtils.printTheadLog("主线程继续");
        CommonUtils.sleepSecond(4);
        CommonUtils.printTheadLog("主线程结束");
    }
}

2.supplyAsync

开启一个有返回值的异步任务

public class SupplyAsyncDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CommonUtils.printTheadLog("主线程 start");
        CompletableFuture<String> future = CompletableFuture
                .supplyAsync(() -> CommonUtils.readFile("news.txt"));
        CommonUtils.printTheadLog("主线程继续");
        System.out.println("news  :" +future.get() );
        CommonUtils.printTheadLog("主线程 end");
    }
}

3.回调函数

1.thenApply

接收上一个异步任务的返回值, 并自己也有返回值的回调

2.thenAccept

接收上一个异步任务的返回值, 但自己无返回值的回调

3.thenRun

不接受上一个异步任务的返回值,也没有返回值

4.编排异步任务

1.thenCompose 两个依赖的异步任务

 

2.thencombine 两个不依赖的异步任务

 3.编排多个异步任务

1.allof 无返回值

get会抛异常 join不会

 

 

2.anyof 有返回值

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Java狂魔哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值