Middle
Can submit be used to run only Runnable or also Callable?
sobes.tech AI
Answer from AI
The submit method from ExecutorService in Java can accept both Runnable and Callable.
- If you pass a
Runnable, the method returns aFuture<?>, which can be used to track the completion of the task, but the result will benull. - If you pass a
Callable<V>, thensubmitreturns aFuture<V>, whereVis the type of the result returned by the task.
Example:
ExecutorService executor = Executors.newFixedThreadPool(2);
// Runnable
Future<?> future1 = executor.submit(() -> System.out.println("Runnable task"));
// Callable
Future<Integer> future2 = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
Integer result = future2.get(); // result will be 42
executor.shutdown();