简体   繁体   中英

Get Callable value using CompletableFuture or Future Object

Future.get() method is a blocking method, I just want my main method to not bother for f.get() and continue with its execution.

How to get the callable returned value from Future or CompletableFuture without compromising with main thread execution and without using any loop for constantly checking using isDone()

        FutureTask<String> result = (FutureTask<String>) es.submit(new Helloo());
//      CompletableFuture<String> r =  CompletableFuture.supplyAsync(()a -> new Hello(), es);
        Future<String> r = es.submit(new Hello());
        es.execute(()->{System.out.println("hello");});
                System.out.println("Main");

                System.out.println("Main");
                System.out.println("Main");
                System.out.println("Main");
                System.out.println(r.get());

                System.out.println("Main");
                System.out.println("Main");```

If you want to supply (calculate/generate/retrieve/etc.) some value then do something with that value asynchronously, you can create a CompletableFuture via a method such as CompletableFuture.supplyAsync . This will return an instance of CompletableFuture .

With that instance, you can call the method thenAccept , which will call the given Consumer method, with the value supplied by the previous step as the argument.

So something kind of like this:

CompletableFuture.supplyAsync(aMethodThatWillReturnAString, yourExecutor).thenAccept((string theString) -> {
    System.out.println(theString);
});

I assume you mean the callback of the CompletableStage? Something like CompletableFuture r = CompletableFuture.supplyAsync(()a -> new Hello()).thenAccept(s -> s + World());

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