java8异步方法CompletableFuture.runAsync不运行

非常基本的代码可以运行异步方法。 当我运行以下代码时,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 ");
        });

    }
}

我希望首先获得“同步命令”,然后获得“异步命令” 但只收到同步消息

caoiq 回答:java8异步方法CompletableFuture.runAsync不运行

您的任务将在其他Thread中运行(默认情况下在Thread中的ForkJoinPool中运行),而您不必等待任务完成-主Thread结束在执行/提交异步任务之前。您可以调用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

或类似:

CompletableFuture<Void> cf = CompletableFuture.runAsync(() -> {
   //...
});

cf.join();
,

它确实可以运行,但是它可以在另一个线程上运行,并且您无需等待结果或对该结果做任何事情。正如CompletableFuture.runAsync()的Javadoc所说:

  

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

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

// 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);
,

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

public static void main(String[] args) {
    CompletableFuture<Void> future = runAsync("run async command ans wait 10000");
    future.join();
    System.out.println("sync commands ");
}

public static CompletableFuture<Void> runAsync(String inputStr) {
    return 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 ");
    });
}
本文链接:https://www.f2er.com/3154078.html

大家都在问