CompletableFuture使用方法

一、为什么使用CompletableFuture

JDK5新增了Future接口,用于描述一个异步计算的结果。使用Future获得异步执行结果时,要么调用阻塞方法get(),要么轮询看isDone()是否为true,这两种方法都不是很好,因为主线程也会被迫等待。

从Java 8开始引入了CompletableFuture,它针对Future做了改进,可以传入回调对象,当异步任务完成或者发生异常时,自动调用回调对象的回调方法。

二、基本方法

当我们想要异步处理时,以前都是调用execute或subject方法,而CompletableFuture有自己的一些方法可以异步执行线程

2.1 runAysnc(无返回值)

CompletableFuture<Void> hello = CompletableFuture.runAsync(
            () -> System.out.println("hello"));

2.2 supplyAsync (有返回值)

CompletableFuture<String> result = CompletableFuture.supplyAsync(
          () -> "sada");
        System.out.println(result.join());

2.3 thenRun (顺序执行,无入参和返回. 第二个任务使用的是调用第一个任务的线程)

     CompletableFuture.runAsync(()-> System.out.println("test1"+
     Thread.currentThread().getName())).thenRun(()->System.out.println("test2"+
     Thread.currentThread().getName()));

2.4 thenRunAsync(第二个任务使用的是默认的ForkJoin线程池)

  CompletableFuture.runAsync(()-> System.out.println("test1"+Thread.currentThread().getName())).thenRunAsync(()->
                System.out.println("test2"+Thread.currentThread().getName()));

2.5 thenAccept(接收参数不返回)

CompletableFuture.supplyAsync(() -> "hello world").thenAccept( s -> System.out.println( s + " test"));

2.6 thenApply(接收参数并返回)

 CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> "aaa").thenApply(s -> "sa" + s);
        System.out.println(stringCompletableFuture.join());

2.7 thenCombine(任务的合并,有返回值)

    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "zhang");
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " san");
        CompletableFuture<String> my = future.thenCombine(future1, (f1, f2) -> f1 + f2);
        System.out.println(my.join());  // zhang san

2.8 thenAcceptBoth (任务的合并,无返回值)

 CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "zhang");
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " san");
        future.thenAcceptBoth(future1, (f1, f2) -> System.out.println(f1+f2));

2.9 acceptEither(无返回值,任意一个任务执行完成就结束)

    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "zhang");
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " san");
        future.acceptEither(future1,x -> System.out.println(x));

2.10 applyToEither(有返回值,任意一个任务执行完成就结束)

  CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> getUser());
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " san");
        CompletableFuture<String> resultFuture = future.applyToEither(future1, x -> x);
        System.out.println(resultFuture.join());

3、实际操作

@GetMapping("test")
    public List<String> test(){
        long start = System.currentTimeMillis();
        List<String> s = new ArrayList<>();
        s.add("a");
        s.add("b");
        s.add("c");
        s.add("d");
        List<CompletableFuture<String>> completableFutureList = s.stream().map(str -> CompletableFuture.supplyAsync(()
                -> testService.getUsername(str))).collect(Collectors.toList());
        List<String> userList = completableFutureList.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
        System.out.println(System.currentTimeMillis()-start+"ms");
        return userList;
    }

你可能感兴趣的:(java,开发语言,后端)