• Java组合异步编程(2)


    您好,我是湘王,这是我的CSDN博客,欢迎您来,欢迎您再来~

    多数码农在开发的时候,要么处理同步应用,要么处理异步。但是如果能学会使用CompletableFuture,就会具备一种神奇的能力:将同步变为异步(有点像用了月光宝盒后同时穿梭在好几个时空的感觉)。怎么做呢?来看看代码。

    新增一个商店类Shop:

    1. /**
    2. * 商店类
    3. *
    4. * @author 湘王
    5. */
    6. public class Shop {
    7. private String name = "";
    8. public Shop(String name) {
    9. this.name = name;
    10. }
    11. public String getName() {
    12. return name;
    13. }
    14. public void setName(String name) {
    15. this.name = name;
    16. }
    17. private double calculatePrice(String product) {
    18. delay();
    19. return 10 * product.charAt(0);
    20. }
    21. private void delay() {
    22. try {
    23. Thread.sleep(1000);
    24. } catch (InterruptedException e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. // 同步得到价格
    29. public double getPrice(String word) {
    30. return calculatePrice(word);
    31. }
    32. // 增加异步查询:将同步方法转化为异步方法
    33. public Future getPriceAsync(String product) {
    34. CompletableFuture future = new CompletableFuture<>();
    35. new Thread(() -> {
    36. double price = calculatePrice(product);
    37. // 需要长时间计算的任务结束并返回结果时,设置Future返回值
    38. future.complete(price);
    39. }).start();
    40. // 无需等待还没结束的计算,直接返回future对象
    41. return future;
    42. }
    43. }

    然后再增加两个测试方法,一个同步,一个异步,分别对应商店类中的同步和异步方法:

    1. // 测试同步方法
    2. public static void testGetPrice() {
    3. Shop friend = new Shop("某宝");
    4. long start = System.nanoTime();
    5. double price = friend.getPrice("MacBook pro");
    6. System.out.printf(friend.getName() + " price is: %.2f%n", price);
    7. long invocationTime = (System.nanoTime() - start) / 1_000_000;
    8. System.out.println("同步调用花费时间:" + invocationTime + " msecs");
    9. // 其他耗时操作(休眠)
    10. doSomethingElse();
    11. long retrievalTime = (System.nanoTime() - start) / 1_000_000;
    12. System.out.println("同步方法返回所需时间:" + retrievalTime + " msecs");
    13. }
    14. // 测试异步方法
    15. public static void testGetPriceAsync() throws InterruptedException, ExecutionException {
    16. Shop friend = new Shop("某东");
    17. long start = System.nanoTime();
    18. Future futurePrice = friend.getPriceAsync("MacBook pro");
    19. long invocationTime = (System.nanoTime() - start) / 1_000_000;
    20. System.out.println("异步方法花费时间:" + invocationTime + " msecs");
    21. // 其他耗时操作(休眠)
    22. doSomethingElse();
    23. // 从future对象中读取价格,如果价格未知,则发生阻塞
    24. double price = futurePrice.get();
    25. System.out.printf(friend.getName() + " price is: %.2f%n", price);
    26. long retrievalTime = (System.nanoTime() - start) / 1_000_000;
    27. System.out.println("异步方法返回所需时间:" + retrievalTime + " msecs");
    28. }

    这里之所以采用微秒,是因为代码量太少的缘故,如果用毫秒根本看不出来差别。运行之后会发现异步的时间大大缩短。

    假设现在咱们做了一个网站,需要针对同一个商品查询它在不同电商平台的价格(假设已经实现了这样的接口),那么显然,如果想查出所有平台的价格,需要一个个地调用,就像这样(为了效果更逼真一些,将返回的价格做了一些调整):

    1. private double calculatePrice(String product) {
    2. delay();
    3. return new Random().nextDouble() * product.charAt(0) * product.charAt(1);
    4. }
    5. /**
    6. * 测试客户端
    7. *
    8. */
    9. public class ClientTest {
    10. private List shops = Arrays.asList(
    11. new Shop("taobao.com"),
    12. new Shop("tmall.com"),
    13. new Shop("jd.com"),
    14. new Shop("amazon.com")
    15. );
    16. // 根据名字返回每个商店的商品价格
    17. public List findPrice(String product) {
    18. List list = shops.stream()
    19. .map(shop ->
    20. String.format("%s price is %.2f RMB",
    21. shop.getName(), shop.getPrice(product)))
    22. .collect(Collectors.toList());
    23. return list;
    24. }
    25. // 同步方式实现findPrices方法,查询每个商店
    26. public void test() {
    27. long start = System.nanoTime();
    28. List list = findPrice("IphoneX");
    29. System.out.println(list);
    30. System.out.println("Done in " + (System.nanoTime() - start) / 1_000_000 + " ms");
    31. }
    32. public static void main(String[] args) {
    33. ClientTest client = new ClientTest();
    34. client.test();
    35. }
    36. }

    由于调用的是同步方法,因此结果查询较慢——叔可忍婶不能忍!

    如果可以同时查询所有的电商平台是不是会快一些呢?可以试试,使用流式计算中的并行流:

    1. // 根据名字返回每个商店的商品价格
    2. public List findPrice(String product) {
    3. List list = shops.parallelStream()// 使用并行流
    4. .map(shop ->
    5. String.format("%s price is %.2f RMB",
    6. shop.getName(), shop.getPrice(product)))
    7. .collect(Collectors.toList());
    8. return list;
    9. }

    改好之后再试一下,果然快多了!

    可以用咱们学过的CompletableFuture再来把它改造一下:

    1. // 使用CompletableFuture发起异步请求
    2. // 这里使用了两个不同的Stream流水线,而不是在同一个处理流的流水线上一个接一个地放置两个map操作
    3. // 这其实是有原因的:考虑流操作之间的延迟特性,如果在单一流水线中处理流,发向不同商家的请求只能以同步、顺序执行的方式才会成功
    4. // 因此,每个创建CompletableFuture对象只能在前一个操作结束之后执行查询指定商家的动作、通知join()方法返回计算结果
    5. public List findPrice(String product) {
    6. List> futures =
    7. shops.parallelStream()
    8. .map(shop -> CompletableFuture.supplyAsync(
    9. () -> String.format("%s price is %.2f RMB",
    10. shop.getName(), shop.getPrice(product))))
    11. .collect(Collectors.toList());
    12. return futures.stream()
    13. // 等待所有异步操作结束(join和Future接口中的get有相同的含义)
    14. .map(CompletableFuture::join)
    15. .collect(Collectors.toList());
    16. }

    这样一来,新的CompletableFuture对象只有在前一个操作完全结束之后,才能创建。而且使用两个不同的Stream流水线,也可以让前一个CompletableFuture在还未执行完成时,就创建新的CompletableFuture对象。它的执行过程就像下面这样:

     

    还有没有改进空间呢?当然是有的!但是代码过于复杂,而且在多数情况下,上面列举出的所有代码已经足够解决实际工作中90%的问题了。不过还是把CompletableFuture结合定制Executor的代码贴出来,这样也有个大致的概念(不鼓励钻牛角尖)。

    1. // 使用定制的Executor配置CompletableFuture
    2. public List findPrice(String product) {
    3. // 为“最优价格查询器”应用定制的执行器Execotor
    4. Executor executor = Executors.newFixedThreadPool(Math.min(shops.size(), 100),
    5. (Runnable r) -> {
    6. Thread thread = new Thread(r);
    7. // 使用守护线程,这种方式不会阻止程序的关停
    8. thread.setDaemon(true);
    9. return thread;
    10. }
    11. );
    12. // 将执行器Execotor作为第二个参数传递给supplyAsync工厂方法
    13. List> futures = shops.stream()
    14. .map(shop -> CompletableFuture.supplyAsync(
    15. () -> String.format("%s price is %.2f RMB",
    16. shop.getName(), shop.getPrice(product)), executor))
    17. .collect(Collectors.toList());
    18. return futures.stream()
    19. // 等待所有异步操作结束(join和Future接口中的get有相同的含义)
    20. .map(CompletableFuture::join)
    21. .collect(Collectors.toList());
    22. }

    这基本上就是CompletableFuture全部的内容了。可以总结一下,对于集合进行并行计算有两种方法:

    1、要么将其转化为并行流,再利用map这样的操作开展工作

    2、要么枚举出集合中的每一个元素,创建新的线程,在CompletableFuture内操作

    CompletableFuture提供了更多的灵活性,它可以调整线程池的大小,确保整体的计算不会因为线程因为I/O而发生阻塞。因此使用建议是:

    1、如果进行的是计算密集型操作,且无I/O操作,那么推荐使用并行parallelStream()

    2、如果并行的计算单元还涉及等待I/O的操作(包括网络连接等待),那么使用CompletableFuture灵活性更好。


    感谢您的大驾光临!咨询技术、产品、运营和管理相关问题,请关注后留言。欢迎骚扰,不胜荣幸~

  • 相关阅读:
    【敏捷那些事儿 03期】一文讲透敏捷的“道、法、术、器”
    【历史上的今天】8 月 31 日:人工智能起源;GPU 诞生;Windows 98 中文版来了
    零基础自学javase黑马课程第八天
    Hive面试题系列第四题-Pv累加趋势图问题
    如何在centos安装python3.8.8?详细教程
    AJAX的Promise(原理)
    Linux——文件编程练手2:修改程序的配置文件
    基于文化算法优化的神经网络预测研究(Matlab代码实现)
    企业快速构建可落地的IT服务管理体系的五大关键点
    知识图谱从入门到应用——知识图谱的发展
  • 原文地址:https://blog.csdn.net/lostrex/article/details/127796502