java8 CompletableFuture,allOf多实例

2018-08-15  本文已影响0人  nickbi
我们在处理业务时,有时会有多任务异步处理,同步返回结果的情况,在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结束后,执行异步方法

上一篇 下一篇

猜你喜欢

热点阅读