java8异步方法CompletableFuture.runAsync无法运行

问题描述 投票:0回答:3

非常基本的代码运行异步方法。当我运行以下代码时,runAsync无法运行。我所缺少的是什么?

结果仅运行同步代码。

public class Main {

    public static void main(String[] args) {
        runAsync("run async command ans wait 10000");

        System.out.println("sync commands ");
    }

    public static void runAsync(String inputStr) {

       CompletableFuture.runAsync(() -> {
            List<String> strings = Arrays.asList(inputStr.split(" "));
            int sleep = Integer.parseInt(strings.get(strings.size() - 1));
            try {
                sleep(sleep);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("async command ");
        });

    }
}

我希望先获得“同步命令”,然后获得“异步命令”但仅获取同步消息

java asynchronous java-8 completable-future
3个回答
1
投票

您的任务将在其他Thread中运行(默认情况下在Thread中的ForkJoinPool中运行),而您不等待其完成-主Thread在执行/提交异步任务之前结束。您可以调用CompletableFuture::join等待它完成,它将阻塞主CompletableFuture::join,直到完成:

Thread

或类似:

CompletableFuture.runAsync(() -> {
        List<String> strings = Arrays.asList(inputStr.split(" "));
        int sleep = Integer.parseInt(strings.get(strings.size() - 1));
        try {
            sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("async command ");
}).join(); //here call the join

0
投票

它确实运行,但是它在另一个线程上运行,您无需等待结果或对结果做任何事情。正如CompletableFuture<Void> cf = CompletableFuture.runAsync(() -> { //... }); cf.join(); 的Javadoc所说:

返回一个新的CompletableFuture,它由运行给定后在ForkJoinPool.commonPool()中运行的任务动作。

CompletableFuture.runAsync()对于不返回任何内容的任务很有用。如果要得到结果,则应使用runAsync(),该结果将返回supplyAsync()然后您可以从中获得结果:

CompletableFuture<T>

0
投票

例如,您需要通过使用join等待异步任务完成:

// Run a task specified by a Supplier object asynchronously
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
    @Override
    public String get() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        return "Result of the asynchronous computation";
    }
});

// Block and get the result of the Future
String result = future.get();
System.out.println(result);
© www.soinside.com 2019 - 2024. All rights reserved.