简体   繁体   中英

CompletableFuture with void methods

I'm looking to run two methods a() and b() that take in no arguments and return nothing (ie void methods) asynchronously such that they are returned in any order concurrently.

However, a third method c() should only run after either of the other above methods complete.

I believe I am supposed to create two CompletableFuture objects (cf1 for a() and cf2 b() ) and then use CompletableFuture.anyOf(cf1, cf2).join() to block the code for c() .

However, I am not sure how to create the cf1 and cf2 CompletableFuture objects. I understand the methods a() and b() are essentially like Runnable's run method but I do not want to change the way they are implemented. Which of CompletableFuture's methods should I call in order to create this CompletableFuture objects for the two methods?

Thank you very much in advance for your help!

If I understand your question correctly, you can do something like this to wait until either of method a() or b() is completed and then once one of them is completed, you run method c() .

CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> a());
CompletableFuture<Void> cf2 = CompletableFuture.runAsync(() -> b());
CompletableFuture<Void> cf3 = CompletableFuture.anyOf(cf1, cf2).thenRunAsync(() -> c());

Or you can directly use runAfterEither as this

    CompletableFuture<Void> a = CompletableFuture.runAsync(() -> {
        Util.delay(new Random().nextInt(1000));
        System.out.println("Hello ");
    });

    a = a.runAfterEither(CompletableFuture.runAsync(() -> {
        Util.delay(new Random().nextInt(1000));
        System.out.println("Hi ");
    }), () -> {
        System.out.println("world"); // your c();
    });

    a.join();

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