The difference between thread execute() and submit()

There are two methods of submitting tasks in the thread pool

The two ways to submit tasks to the thread pool are roughly as follows:
Method 1: Call the execute() method

Method 2: Call the submit() method

1. Difference

What is the difference between the above submit() and execute() methods? There are roughly three points:

1. The parameters received by the two are different

The Execute() method can only receive parameters of the Runnable type, while the submit() method can receive parameters of both Callable and Runnable types. Tasks of the Callable type can return execution results, but tasks of the Runnable type cannot return execution results. Callable is an execution target interface added by JDK 1.5. As a supplement to Runnable, it allows return values ​​and throws exceptions. The main difference between Runnable and Callable is: Callable allows return values, while Runnable does not allow return values; Runnable does not allow exceptions to be thrown, while Callable allows exceptions to be thrown.

2.submit() will have a return value after submitting the task, but execute() does not

The execute() method is mainly used to start the execution of the task, and the caller does not care about the execution result of the task and possible exceptions. The submit() method is also used to start the execution of the task, but after the start, it will return a Future object, which represents an asynchronous execution instance, and the result can be obtained through the asynchronous execution instance.

Submit is acceptable regardless of whether it is a Runnable or Callable task, but the return value of Runnable is void , so the result obtained by using Future 's get() is still null

3.submit() is convenient for Exception handling

After the execute() method starts task execution, the caller does not care about the exceptions that may occur during task execution. The Future object (asynchronous execution instance) returned by the submit() method can capture exceptions during asynchronous execution.

2. Contact

In the implementation of the ThreadPoolExecutor class, the internal core task submission method is the execute() method. Although the user program can also submit tasks through submit(), in fact the execute() method is finally called in the submit() method.

Guess you like

Origin blog.csdn.net/lan861698789/article/details/128805222