Middle
Kas on võimalik käivitada ainult Runnable või ka Callable kasutades submit?
sobes.tech AI
Vastus AI-lt
The submit method of ExecutorService in Java can accept both Runnable and Callable.
- If a
Runnableis passed, the method returns aFuture<?>, which can be used to monitor the completion of the task, but the result will benull. - If a
Callable<V>is passed, 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();