https://www.jianshu.com/p/1db996cf7574
 
我们在处理业务时,有时会有多任务异步处理,同步返回结果的情况,在java中,我们可以使用CompletableFuture的allOf方法来实现多实例的同时返回。
   public void futureTest() {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future1 finished!");
            return "future1 finished!";
        });
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("future2 finished!");
            return "future2 finished!";
        });
        CompletableFuture<Void> combindFuture = CompletableFuture.allOf(future1, future2);
        try {
            combindFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("future1: " + future1.isDone() + " future2: " + future2.isDone());
    }

在这里我们可以将对各future实例添加到allOf方法中,然后通过future的get()方法获取future的状态。如果allOf里面的所有线程为执行完毕,主线程会阻塞,直到allOf里面的所有线程都执行,线程就会被唤醒。

异步编程,不想阻塞线程的话,可以使用thenAccpt、thenApply、thenRun,future结束后,执行异步方法



作者:nickbi
链接:https://www.jianshu.com/p/1db996cf7574
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关文章:

  • 2022-12-23
  • 2021-10-13
  • 2021-07-10
  • 2022-12-23
  • 2021-10-16
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
猜你喜欢
  • 2021-11-04
  • 2021-11-29
  • 2023-04-06
  • 2022-02-27
  • 2019-08-14
  • 2022-12-23
相关资源
相似解决方案