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

前端 未结 8 1404
你的背包
你的背包 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:41

    A main difference between the submit() and execute() method is that ExecuterService.submit()can return result of computation because it has a return type of Future, but execute() method cannot return anything because it's return type is void. The core interface in Java 1.5's Executor framework is the Executor interface which defines the execute(Runnable task) method, whose primary purpose is to separate the task from its execution.

    Any task submitted to Executor can be executed by the same thread, a worker thread from a thread pool or any other thread.

    On the other hand, submit() method is defined in the ExecutorService interface which is a sub-interface of Executor and adds the functionality of terminating the thread pool, along with adding submit() method which can accept a Callable task and return a result of computation.

    Similarities between the execute() and submit() as well:

    1. Both submit() and execute() methods are used to submit a task to Executor framework for asynchronous execution.
    2. Both submit() and execute() can accept a Runnable task.
    3. You can access submit() and execute() from the ExecutorService interface because it also extends the Executor interface which declares the execute() method.

    Apart from the fact that submit() method can return output and execute() cannot, following are other notable differences between these two key methods of Executor framework of Java 5.

    1. The submit() can accept both Runnable and Callable task but execute() can only accept the Runnable task.
    2. The submit() method is declared in ExecutorService interface while execute() method is declared in the Executor interface.
    3. The return type of submit() method is a Future object but return type of execute() method is void.

提交回复
热议问题