submit()
is an instance method that takes a callable task as a parameter for execution and returns a Future
.
Refer to What is the difference between runnable and callable in Java? to understand more about
Callable
in Java.
<T> Future<T> submit(Callable<T> task)
Callable<T> task
: The callable task to execute.This method returns a Future
.
import java.util.concurrent.*; public class Main { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newSingleThreadExecutor(); Callable<String> stringCallable = () -> "Callable called"; Future<String> callableFuture = executorService.submit(stringCallable); System.out.println("Result of the callable - " + callableFuture.get()); executorService.shutdown(); } }
executorService
.stringCallable
that returns a string value.stringCallable
to the executorService
using the submit()
method. The submit()
method returns a Future
.Future
obtained in line 10 using the get()
method and print the result. (To learn more about the Future.get()
method in Java, read this shot.)RELATED TAGS
CONTRIBUTOR
View all Courses