为了账号安全,请及时绑定邮箱和手机立即绑定

Java组合异步编程(2)

标签:
Java

您好,我是湘王,这是我的慕课手记,欢迎您来,欢迎您再来~


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

新增一个商店类Shop

/**
 * 商店类
 *
 * @author 湘王
 */
public class Shop {
    private String name = "";

    public Shop(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private double calculatePrice(String product) {
        delay();
        return 10 * product.charAt(0);
    }

    private void delay() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 同步得到价格
    public double getPrice(String word) {
        return calculatePrice(word);
    }

    // 增加异步查询:将同步方法转化为异步方法
    public Future<Double> getPriceAsync(String product) {
        CompletableFuture<Double> future = new CompletableFuture<>();
        new Thread(() -> {
            double price = calculatePrice(product);
            // 需要长时间计算的任务结束并返回结果时,设置Future返回值
            future.complete(price);
        }).start();

        // 无需等待还没结束的计算,直接返回future对象
        return future;
    }
}


 

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

// 测试同步方法
public static void testGetPrice() {
   Shop friend = new Shop("某宝");
   long start = System.nanoTime();
   double price = friend.getPrice("MacBook pro");
   System.out.printf(friend.getName() + " price is: %.2f%n", price);
   long invocationTime = (System.nanoTime() - start) / 1_000_000;
   System.out.println("同步调用花费时间:" + invocationTime + " msecs");

   // 其他耗时操作(休眠)
   doSomethingElse();

   long retrievalTime = (System.nanoTime() - start) / 1_000_000;
   System.out.println("同步方法返回所需时间:" + retrievalTime + " msecs");
}

// 测试异步方法
public static void testGetPriceAsync() throws InterruptedException, ExecutionException {
   Shop friend = new Shop("某东");
   long start = System.nanoTime();
   Future<Double> futurePrice = friend.getPriceAsync("MacBook pro");
   long invocationTime = (System.nanoTime() - start) / 1_000_000;
   System.out.println("异步方法花费时间:" + invocationTime + " msecs");

   // 其他耗时操作(休眠)
   doSomethingElse();

   // 从future对象中读取价格,如果价格未知,则发生阻塞
   double price = futurePrice.get();
   System.out.printf(friend.getName() + " price is: %.2f%n", price);

   long retrievalTime = (System.nanoTime() - start) / 1_000_000;
   System.out.println("异步方法返回所需时间:" + retrievalTime + " msecs");
}


 


 

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

 

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

private double calculatePrice(String product) {
    delay();
    return new Random().nextDouble() * product.charAt(0) * product.charAt(1);
}



/**
 * 测试客户端
 *
 */
public class ClientTest {
   private List<Shop> shops = Arrays.asList(
      new Shop("taobao.com"),
      new Shop("tmall.com"),
      new Shop("jd.com"),
      new Shop("amazon.com")
   );

   // 根据名字返回每个商店的商品价格
   public List<String> findPrice(String product) {
      List<String> list = shops.stream()
                        .map(shop ->
                           String.format("%s price is %.2f RMB",
                           shop.getName(), shop.getPrice(product)))
                        .collect(Collectors.toList());
      return list;
   }

   // 同步方式实现findPrices方法,查询每个商店
   public void test() {
      long start = System.nanoTime();
      List<String> list = findPrice("IphoneX");

      System.out.println(list);
      System.out.println("Done in " + (System.nanoTime() - start) / 1_000_000 + " ms");
   }

   public static void main(String[] args) {
      ClientTest client = new ClientTest();
      client.test();
   }
}

 


 

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

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

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

 

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

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

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

 

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

https://img1.sycdn.imooc.com//636cf9ff0001863e07650609.jpg

 

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

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

 

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

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

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

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

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

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

 



 

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




点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消