异步编程

时间:2018-03-27 06:29:37

标签: java asynchronous java-8 completable-future

我正在尝试使用以下代码来学习Java 8.

此代码的输出为:

Before Get
Rajeev , Welcome to the CalliCoder Blog
After Get.

但根据我对异步程序的理解,输出应该是

类似:

Before Get
After Get. 
Rajeev , Welcome to the CalliCoder Blog

对此plz的任何评论。

 public static void main(String[] args) throws InterruptedException, ExecutionException {

    CompletableFuture<String> welcomeText = CompletableFuture.supplyAsync(() -> {

        for(double i=0;i<1000000000;i++) {
            for(double j=0;i<1000000000;i++) {
                for(double k=0;i<1000000000;i++) {
                    for(double l=0;i<1000000000;i++) {
                        for(double m=0;i<1000000000;i++) {
                            for(double n=0;i<1000000000;i++) {
                                for(double o=0;i<1000000000;i++) {

                                }
                            }
                        }
                    }
                }
            }
        }
        return "Rajeev";
    }).thenApply(name -> {
        return "Hello " + name;
    }).thenApply(greeting -> {
        return greeting + ", Welcome to the CalliCoder Blog";
    });
    System.out.println("Before Get");
    System.out.println(welcomeText.get());
    System.out.println("After Get");
}

2 个答案:

答案 0 :(得分:0)

welcomeText.get()的调用会阻塞,直到结果可用。

异步编程并不意味着事情只是以随机顺序发生而且很好。您必须拥有一个受益于异步执行的任务。这个例子与任何事情无关。

答案 1 :(得分:0)

如果我们正在学习异步编程,那么你最初是否正确调用.get()并没有真正意义。

在大多数异步方案中,您真的不需要使用.get(),通常会使用whenComplete()

类似的东西:

.whenComplete((s,e) -> {System.out.println("Really Done -> " + s );});

注释掉get()并将Thread.Sleep(10)放在main()中,通常异步是关于异步IO和CPU密集型操作实际上并不需要异步。如果你在java中查看netty和其他异步库,你会更加欣赏它。