Middle
Com o submit, é possível lançar apenas Runnable ou também Callable?
sobes.tech IA
Resposta da IA
O método submit do ExecutorService em Java pode aceitar tanto Runnable como Callable.
- Se passar um
Runnable, o método retorna umFuture<?>, que pode ser usado para acompanhar a conclusão da tarefa, mas o resultado seránull. - Se passar um
Callable<V>, entãosubmitretorna umFuture<V>, ondeVé o tipo de resultado retornado pela tarefa.
Exemplo:
ExecutorService executor = Executors.newFixedThreadPool(2);
// Runnable
Future<?> future1 = executor.submit(() -> System.out.println("Tarefa Runnable"));
// Callable
Future<Integer> future2 = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
Integer result = future2.get(); // result será 42
executor.shutdown();