JUC异步编程

本文介绍了Java并发编程工具包JUC,讲解了异步编程的概念,并详细探讨了CompletableFuture的使用,包括runAsync和supplyAsync方法,任务串行化,以及如何处理多个任务的组合。此外,还涉及了Java的定时调度机制ScheduledExecutorService,请求合并的策略以及Fork/Join框架在任务分割和合并结果中的应用。
摘要由CSDN通过智能技术生成

什么是JUC

JUC的意思是java并发编程工具包,是java.util.concurrent包的简称。目的就是为了更好的支持高并发任务,让开发者利用这个包进行的多线程开发时,可以有效的减少竞争条件和死锁线程。

异步编程

模拟用户下单操作。。。

1、根据地址id查询地址信息 -- > 0.5s

2、查询用户购物车的数据 -- >0.5s

3、查询购物车中的商品信息 -- > 1s

4、创建订单 -- > 0.5s

5、创建订单详情 --> 0.5s

用户创建要给一个订单总共耗时3s,没给操作都是同步执行的。如果变成异步是否会提高性能?

CompletableFuture

Java8新增了CompletableFuture 提供对异步计算的支持,可以通过回调的方式处理计算结果。

runAsync 和 supplyAsync方法

public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

CompletableFuture 提供了四个静态方法来创建一个异步操作。

没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。以下所有的方法都类同。

runAsync方法不支持返回值。

supplyAsync可以支持返回值。

使用默认和指定的线程池

       // 创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        System.out.println("线程开始。。。");

        // 使用默认的线程池
        CompletableFuture.runAsync(() -> {
            System.out.println("任务开始执行。。");
        });

        // 使用指定的线程池
        CompletableFuture.runAsync(() ->{
            System.out.println("任务2开始执行。。。");
        },executorService);

        System.out.println("线程结束");

线程执行完后有返回值

   		 // 创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        System.out.println("线程开始。。。");

		// 使用指定线程池运行一个任务
       CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            Integer sum = 0;
            for (int i = 1; i <=5; i++) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sum += i;
            }
            return sum;
        }, executorService);

		// get()阻塞等结果
        System.out.println("sum:"+voidCompletableFuture.get());
        System.out.println("线程结束");

计算结果完成时的回调方法

当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:

public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)

可以看到Action的类型是BiConsumer<? super T,? super Throwable>它可以处理正常的计算结果,或者异常情况。

whenComplete 和 whenCompleteAsync 的区别:

whenComplete:是执行当前任务的线程继续执行 whenComplete 的任务。

whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。

exceptionally:任务运行出现异常后调用,在这个方法里面可以改变任务的返回值(降级)。

        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务线程:"+Thread.currentThread().getName());
            Integer sum = 0;
            for (int i = 1; i <= 5; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int x = 10 / 0;
                sum += i;
            }
            return sum;
        }, executorService).whenComplete((resp, exc) -> {
//            System.out.println("任务执行完了,返回结果是:" + resp + ",异常:" + exc);
            System.out.println("whenComplete:"+Thread.currentThread().getName());
        }).whenCompleteAsync((resp,exc)->{
            System.out.println("whenCompleteAsync:"+Thread.currentThread().getName());
        },executorService).exceptionally((exc) -> {
//            System.out.println("出现异常了,这个方法里面可以修改返回结果");
            return 20;
        });
        System.out.println("sum:" + integerCompletableFuture.get());

handle

handle 是执行任务完成时对结果的处理。

exceptionally和handle同时存在,handle 的返回值会覆盖掉exceptionally的。whenCompleteAsync是感知任务执行完了,而handle是任务执行完了真真的调用

   CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务线程:"+Thread.currentThread().getName());
            Integer sum = 0;
            for (int i = 1; i <= 5; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int x = 10 / 0;
                sum += i;
            }
            return sum;
        }, executorService).handle((resp,exc)->{
            System.out.println("handle:resp:"+resp+",exc:"+exc);
            return 22;
        });
        System.out.println("sum:" + integerCompletableFuture.get());

任务串行化

前一个任务执行完才能执行后一个任务。

// 接收前一个任务的执行结果,并消费处理,该任务没有返回结果 ,可以接收到上一个任务的异常
public CompletionStage<T>  whenComplete(BiConsumer action)
public CompletionStage<T>  whenCompleteAsync(BiConsumer action)
public Co
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值