Java异步CompletableFuture的使用

  所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法。Java中的CompletableFuture 提供了四个静态方法来创建一个异步操作。

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

  没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。其中:

  runAsync方法不支持返回值。

  supplyAsync可以支持返回值。

  如下:

//无返回值
public static void runAsync() throws Exception {
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
        try {
            System.out.println("run start ...");
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
        }
        System.out.println("run end ...");
    });
    
    future.get();
}

//有返回值
public static void supplyAsync() throws Exception {         
    CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
        try {
            System.out.println("run start ...");
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
        }
        System.out.println("run end ...");
        return System.currentTimeMillis();
    });

    long time = future.get();
    System.out.println("time = "+time);
}

  今天写到这里,简单的使用如上代码,后续会有更新。

猜你喜欢

转载自www.cnblogs.com/JohanChan/p/11251080.html