简体   繁体   中英

CompletableFuture blocks main thread

I know that get() method from CompletableFuture blocks thread, but how can I achieve executing System.out.println("xD") while Future is processing, because right now this statement is executed when CompletableFuture is completed.

import java.util.concurrent.*;
import java.util.stream.Stream;

public class CompletableFutureTest {


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(CompletableFutureTest::counting).whenComplete((result, exception) -> {
            if (exception != null) {
                System.out.println(result);
            } else {
            }
        }).get();

        System.out.println("xD");
    }


    public static int counting() {

        Stream.iterate(1, integer -> integer +1).limit(5).forEach(System.out::println);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 10;
    }
}

You should move get() right after the print statement.
This way, the print will be performed while the value from the future is being evaluated.

public static void main(String[] args) throws ExecutionException, InterruptedException {
    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(CompletableFutureTest::counting).whenComplete((result, exception) -> {
        if (exception != null) {
            System.out.println(result);
        } else {
        }
    });

    System.out.println("xD");
    Integer value = future.get();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM