异步编程三:CompletableFuture异步编程

87 阅读1分钟

runAsync:无入参、无返回值

CompletableFuture.runAsync()  方法用于执行没有返回值的任务。

public class CompletableFutureRunAsyncDemo {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        System.out.println("main start ...");

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("开启异步任务...");
        }, executor);

        System.out.println("main end ...");

        executor.shutdown();

    }
}

执行结果:

main start ...

main end ...

开启异步任务...

supplyAsync :无入参,可以获取返回值

使用CompletableFuture.supplyAsync()  方法来创建 CompletableFuture 对象的示例

public class CompletableFutureSupplyAsyncDemo {

    public static void main(String[] args) throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        System.out.println("main start ...");
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("开启异步任务...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "开启异步任务,我是返回值";
        }, executor);

        System.out.println("main here are not blocked ...");
        System.out.println("获取异步任务返回值:" + future.get());
        System.out.println("main end ...");

        executor.shutdown();

    }
}

执行结果:

main start ...
main here are not blocked ...
开启异步任务...
获取异步任务返回值:开启异步任务,我是返回值
main end ...