What is the difference between ExecutorService.submit and ExecutorService.execute in this code in Java?

前端 未结 8 1336
你的背包
你的背包 2021-01-30 00:05

I am learning to use ExectorService to pool threads and send out tasks. I have a simple program below

import java.util.concurrent.Execu         


        
8条回答
  •  醉酒成梦
    2021-01-30 00:25

    The execute(Runnable command) is the implemented method from Interface Executor. It means just execute the command and gets nothing returned.

    ExecutorService has its own methods for starting tasks: submit, invokeAny and invokeAll all of which have Callable instances as their main targets. Though there're methods having Runnable as input, actulaly Runnable will be adapted to Callable in the method. why Callable? Because we can get a Future result after the task is submitted.

    But when you transform a Runnable to a Callable, result you get is just the value you pass:

    static final class RunnableAdapter implements Callable {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
    }
    

    So, what's the point that we pass a Runnable to submit instead of just getting the result when the task is finished? Because there's a method which has only Runnable as parameter without a particular result.

    Read the javadoc of Future:

    If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future and return null as a result of the underlying task.

    So, if you just want to execute a Runnable task without any value returned, you can use execute().

    if you want to run a Callable task, or

    if you want to run a Runnable task with a specified result as the completion symbol, or

    if you want to run a task and have the ability to cancel it,

    you should use submit().

提交回复
热议问题