CompletableFuture

CompletableFuture 并发处理任务

CompletableFuture.completeExceptionally(Exception e) 记录异常

CompletableFuture.supplyAsync(Supplier s) 利用Lambda异步处理

package CompletableFuture;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Shop {
    // 同步查询价格
    public double getPrice(String product, int platform) {
        return calculate(product);
    }

    // 异步查询价格
    public Future<Double> getPriceByAsync(String product, int platform) {
        CompletableFuture<Double> future = new CompletableFuture<>();
        new Thread(() -> {
            double price = calculate(product);
            future.complete(price);
        }).start();
        return future;
    }

    // Lambda 异步查询价格,默认利用ForkJoinPool调用自任务
    public Future<Double> getPriceByAsyncLambda(String product, int platform) {
        CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> calculate(product));
        return future;
    }

    // 利用CompletableFuture.completeExceptionally记录子任务异常
    public Future<Double> getPriceByAsyncWithException(String product, int platform) {
        CompletableFuture<Double> future = new CompletableFuture<>();
        new Thread(() -> {
            try {
                double price = calculate(product);
                throw new RuntimeException("Future task thread throw exception");
                // future.complete(price);
            } catch (Exception e) {
                future.completeExceptionally(e);
            }
        }).start();
        return future;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 同步耗时测试
         */
        Shop shop = new Shop();
        long start = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            shop.getPrice("Durex", i);
        }
        long end = System.nanoTime();
        System.out.println("同步耗时:" + String.valueOf((end - start) / 1000000) + "ms");//同步耗时:5008ms
        /**
         * 异步耗时测试
         */
        List<Future<Double>> durexList = new ArrayList<>();
        start = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            Future<Double> durex = shop.getPriceByAsync("Durex", i);
            durexList.add(durex);
        }
        for (Future<Double> future : durexList) {
            future.get();
        }
        end = System.nanoTime();
        System.out.println("异步耗时:" + String.valueOf((end - start) / 1000000) + "ms");//异步耗时:1012ms
        /**
         * 异常测试
         */
        durexList = new ArrayList<>();
        start = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            Future<Double> durex = shop.getPriceByAsyncWithException("Durex", i);
            durexList.add(durex);
        }
        for (Future<Double> future : durexList) {
            /**
             * 抛出异常:
             * 子任务未将最终结果赋给future:future.complete(price); 而是记录异常future.completeExceptionally(e);
             * 若子线程调用完future.complete(price);之后throw异常,则此处不抛出异常
             *
             * Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.RuntimeException: Future task thread throw exception
             * 	at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
             * 	at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
             * 	at CompletableFuture.Shop.main(Shop.java:76)
             * Caused by: java.lang.RuntimeException: Future task thread throw exception
             * 	at CompletableFuture.Shop.lambda$getPriceByAsyncWithException$1(Shop.java:31)
             * 	at java.base/java.lang.Thread.run(Thread.java:834)
             */
            future.get();
        }
        end = System.nanoTime();
        System.out.println("异步耗时:" + String.valueOf((end - start) / 1000000) + "ms");//异步耗时:1012ms
    }

    public double calculate(String product) {
        delay();
        return new Random().nextDouble() * product.charAt(0) + product.charAt(1);
    }

    public static void delay() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值