zoukankan      html  css  js  c++  java
  • CompletableFuture

    文档地址:
     https://www.matools.com/api/java8
     https://blog.csdn.net/sl1992/article/details/100677099

    package com.example.netty.async;
    
    import java.util.concurrent.*;
    
    /**
     * @author luliang
     * @date 2021-01-25 14:21
     * CompletableFuture;异步执行
     * 文档地址:
     * https://www.matools.com/api/java8
     * https://blog.csdn.net/sl1992/article/details/100677099
     */
    public class CompletableFutureTest {
    
        //一、CompletableFuture的静态方法
        public void staticMethod() {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
    
            //1、异步执行,有返回值,使用ForkJoinPool.commonPool()中的线程
            CompletableFuture.supplyAsync(() -> null);
            //2、异步执行,有返回值,使用Executors中的线程
            CompletableFuture.supplyAsync(() -> null, executorService);
            //3、异步执行,无返回值,使用ForkJoinPool.commonPool()中的线程
            CompletableFuture.runAsync(() -> {
            });
            //4、异步执行,无返回值,使用Executors中的线程
            CompletableFuture.runAsync(() -> {
            }, executorService);
            //3、使用给定值进行操作
            CompletableFuture.completedFuture(1).thenApply((s) -> s + 3);
            //4、当所有给定的CompletableFutures完成时
            CompletableFuture.allOf();
            //5、当任何一个给定的CompletableFutures完成
            CompletableFuture.anyOf();
        }
    
        //二、普通方法
        public static void method(CompletableFuture<Integer> futureA, CompletableFuture<Integer> futureB) throws Exception {
            /**
             * 哪个线程跑的最快用那个,无返回值
             * 1、supplyAsync与acceptEitherAsync(默认的线程池)与acceptEitherAsync(给定的线程池)
             */
            CompletableFuture<Void> futureVoid = futureB.acceptEitherAsync(futureA, (s) -> System.out.println(s));
    
            /**
             * 哪个线程跑的最快用那个,有返回值
             * 2、applyToEither与applyToEitherAsync(默认的线程池)与applyToEitherAsync(给定的线程池)
             */
            CompletableFuture<Integer> futureC = futureB.applyToEitherAsync(futureA, (o -> o));
    
            /**
             * 3、终止任务,如果未完成,抛出CancellationException
             */
            //futureB.cancel(true);
            /**
             * 4、终止任务,返回给定的值
             */
            futureB.complete(99);
            /**
             * 5、终止任务,如果未完成,调用 get()和相关方法时抛出指定异常信息
             */
            futureB.completeExceptionally(new Exception("结束异常"));
            /**
             * 6、如果CompletableFuture出现异常,则执行exceptionally,否则正常返回
             * exceptionally
             */
            CompletableFuture<Integer> futureAll = CompletableFuture.supplyAsync(() -> 1 / 1).exceptionally((t) -> {
                System.out.println("异常信息" + t);
                return 10;
            });
            /**
             * 7、获取执行结果,会阻塞,抛出异常
             */
            futureB.get();
            /**
             * 8、获取执行结果,设置等待时间(超时时间)
             */
            futureB.get(1, TimeUnit.MINUTES);
            /**
             * 9、获取执行结果,如果执行完成则返回结果或抛出异常,否则返回给定值
             */
            futureA.getNow(100);
            /**
             *10、将CompletableFuture执行结果或异常信息作为参数,进行执行
             * handle、handleAsync(默认线程池)、handleAsync(自定义线程池)
             */
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10 / 0);
            future.handle((s, t) -> {
                System.out.println("参数" + s);
                System.out.println("异常信息" + t);
                return null;
            });
            /**
             * 11、如果以任何方式完成,返回true,否则false
             */
            futureA.isDone();
            /**
             * 12、在正常完成之前被取消,则返回 true
             */
            futureA.isCancelled();
            /**
             * 13、以任何方式异常完成包括取消,则返回true
             */
            futureA.isCompletedExceptionally();
            /**
             * 14、获取执行结果,没有检查异常,不会强制抛出异常
             */
            Integer join = futureA.join();
            /**
             * 15、强制返回结果,不管是否执行完成
             */
            futureA.obtrudeValue(100);
            /**
             * 16、强制抛出异常,无论是否执行完成
             */
            futureA.obtrudeException(new Exception("异常"));
            /**
             *17、两个异步线程都执行完毕后,执行线程C
             * runAfterBoth、runAfterBothAsync(默认线程池)、runAfterBothAsync(自定义线程池)
             */
            futureA.runAfterBoth(futureB, () -> {
            });
            /**
             * 18、两个线程有任何一个执行完毕,执行线程C
             * runAfterEither、runAfterEitherAsync(默认线程池)、runAfterEitherAsync(自定义线程池)
             */
            futureA.runAfterEither(futureB, () -> {
            });
            /**
             * 19、当此阶段正常完成时,将以该阶段的结果作为参数执行,无返回值
             * thenAccept、thenAcceptAsync(默认线程池)、thenAcceptAsync(自定义线程池)
             */
            futureA.thenAccept((v) -> System.out.println());
            /**
             * 20、当此阶段正常完成时,将以该阶段的结果作为参数执行,有返回值
             * thenApply、thenApplyAsync(默认线程池)、thenApplyAsync(自定义线程池)
             */
            futureA.thenApply((v) -> v);
            /**
             * 21、两个线程执行完毕后,将两个线程的结果作为参数进行执行,无返回值
             * thenAcceptBoth、thenAcceptBothAsync(默认线程池)、thenAcceptBothAsync(自定义线程池)
             */
            futureA.thenAcceptBoth(futureB, (f1, f2) -> {
            });
            /**
             * 22、两个线程执行完毕后,将亮哥哥线程的结果作为参数进行执行,有返回值
             */
            futureA.thenCombine(futureB, (f1, f2) -> null);
            /**
             * 23、此阶段正常完成时,将以该阶段的结果作为参数执行,有返回值
             * thenCompose、thenComposeAsync、thenComposeAsync
             * 不指定泛型,类型为Object,
             */
            futureA.thenCompose((f1) -> null);
            /**
             * 22、正常完成时,执行此操作,无返回值
             * thenRun、thenRunAsync、thenRunAsync
             */
            futureA.thenRun(() -> {
            });
            /**
             * 23、返回此CompletableFuture
             */
            futureA.toCompletableFuture();
            /**
             * 24、当此阶段完成时,以此阶段的结果(如果没有则为null)和异常(如果没有则为null)作为参数来调用给定操作。
             * 返回阶段在操作返回时完成。如果提供的操作本身遇到异常,那么除非此阶段也异常完成,否则返回的阶段将异常完成。
             */
            futureA.whenComplete((f1, t) -> {
            });
        }
    
        public static void main(String[] args) throws Exception {
            CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("A执行完毕" + Thread.currentThread().getId());
                return 1;
            });
            CompletableFuture<Integer> futureB = CompletableFuture.supplyAsync(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("B执行完毕" + Thread.currentThread().getId());
                return 2;
            });
    
            method(futureA, futureB);
            while (true) {
            }
        }
    }
  • 相关阅读:
    mybatis源码阅读-Transaction和TransactionFactory(四)
    mybatis源码阅读-SqlSessionFactory和SqlSession(三)
    mybatis使用-高级用法(二)
    mybatis使用-helloword(一)
    Spring Boot-全局异常处理(八)
    Spring Boot-定义拦截器(七)
    Spring Boot-整合redis(六)
    Spring Boot-热部署和Debugger使用(三)
    Spring Boot-整合Mybatis(五)
    netty自定义协议 心跳 断线重连源码
  • 原文地址:https://www.cnblogs.com/luliang888/p/14330392.html
Copyright © 2011-2022 走看看