How to use Callable with void return type?

前端 未结 3 648
时光取名叫无心
时光取名叫无心 2021-02-02 05:21

I am working on a project in which I have multiple interface and two Implementations classes which needs to implement these two interfaces.

Suppose my first Interface is

相关标签:
3条回答
  • 2021-02-02 05:52

    Why would you need a void for running something in Parallel? For one, if you don't need the return value, you can simply return null.

    To make something parallel you need to use threading/scheduling. I would personally recommend avoiding Callables, and using Runnables instead (and hey, no return value).

    0 讨论(0)
  • 2021-02-02 05:56

    A shorter version:

    ExecutorService executor = ... // e.g. Executors.newFixedThreadPool(4);
    Future<?> future = executor.submit(() -> testA.abc());
    testB.xyz();
    future.get(); // wait for completion of testA.abc()
    

    To be noted that having to run something in parallel with nothing to be returned could be a sign of a bad pattern :)

    Also, if you are in a Spring environment, you could use: https://spring.io/guides/gs/async-method/

    0 讨论(0)
  • 2021-02-02 06:04

    You can use java.lang.Thread for parallel execution. However, in most cases it's easier to use an java.util.concurrent.ExecutorService. The latter provides a method to submit a Callable and returns a Future to get the result later (or wait for completion).

    If testA.abc() and testB.xyz() should be executed in parallel, you use the ExecutorService to execute the former in a separate thread whereas the latter is executed in the original thread. Then you wait for the completion of the former for synchronization.

    ExecutorService executor = ... // e.g. Executors.newFixedThreadPool(4);
    
    Future<Void> future = executor.submit(new Callable<Void>() {
        public Void call() throws Exception {
            testA.abc();
            return null;
        }
    });
    testB.xyz();
    future.get(); // wait for completion of testA.abc()
    
    0 讨论(0)
提交回复
热议问题