callable()
is a static method of the Executors
class that takes a Runnable
and a value as parameters. It returns a Callable
when called, runs the passed Runnable
task and returns the passed value.
Refer What is the difference between runnable and callable in Java? to understand the difference between
Runnable
andCallable
.
public static <T> Callable<T> callable(Runnable task, T result)
Runnable task
: The runnable task to run.T result
: The value/result to return.This method returns a callable object.
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Main {public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService executorService = Executors.newSingleThreadExecutor();Runnable runnable = () -> System.out.println("Runnable executed");int resultToReturn = -234;Callable<Integer> callable = Executors.callable(runnable, resultToReturn);System.out.println("Return value - " + executorService.submit(callable).get());executorService.shutdown();}}
runnable
that prints a string.resultToReturn
.callable()
method we get a callable object passing runnable
and resultToReturn
as arguments.