I found there are two ways (submit and execute) to add a Runnable into a thread pool, what is the difference?
1) The submit() can accept both Runnable and Callable tasks but execute() can only accept the Runnable task. 2) The submit() method is declared in the ExecutorService interface while the execute() method is declared in the Executor interface.
The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java. util. concurrent package.
Executor just executes stuff you give it. ExecutorService adds startup, shutdown, and the ability to wait for and look at the status of jobs you've submitted for execution on top of Executor (which it extends). This is a perfect answer, short and clear.
The execute() method of ThreadPoolExecutor class executes the given task sometime in the future. The task may execute in a new thread or an existing pooled thread. If the task is not submitted to the pool due to any reason, then the task is handled by the current RejectedExecutionHandler.
The difference is that execute
doesn't return a Future
, so you can't wait for the completion of the Runnable
and get any exception it throws using that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With