Junior — Middle
Какое отличие между методом submit у Executor и методом start у Thread при запуске задач в Java?
sobes.tech AI
Answer from AI
The start() method of the Thread class directly starts a new thread and calls the run() method in that thread. This is a low-level way of creating and starting a thread.
The submit() method of Executor (for example, ThreadPoolExecutor) submits a task (Runnable or Callable) to a thread pool for asynchronous execution. Unlike start(), submit() does not create a new thread directly but uses existing threads from the pool, which is more resource-efficient.
Main differences:
start()launches a new thread each time, which can be resource-intensive.submit()uses a thread pool, reusing threads and managing their number.submit()returns aFuture, allowing you to get the result or check the task's status.
Example:
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<?> future = executor.submit(() -> {
System.out.println("Task is running");
});
Thread thread = new Thread(() -> {
System.out.println("Thread started");
});
thread.start();