Junior — Middle
When is it better to use the submit method from Executor or the start method from Thread to run tasks?
sobes.tech AI
Answer from AI
The start() method of the Thread class is used to directly start a new thread in which a task is executed. This is a low-level way of managing threads, where you explicitly create and start threads.
The submit() method from Executor (for example, ExecutorService) is used to submit tasks for execution in a thread pool. This is a higher-level and more flexible way, allowing you to manage the number of threads, reuse them, and obtain execution results via Future.
When to use:
- If you need to quickly start a simple task in a separate thread and thread management is not required — you can use
Thread.start(). - If the application requires scalability, thread pool management, thread reuse, task execution control, and result retrieval — it is better to use
Executor.submit().
Example with Executor:
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<Integer> future = executor.submit(() -> {
// some task
return 42;
});
Integer result = future.get();
executor.shutdown();