submit, execute, callable, runnable

By | March 10, 2017
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

ExecutorService and ListeningExecutorService has submit() and execute() funciton:

Future<T> submit(Callable<T> task)
Future<?> submit(Runnable task)
void execute(Runnable command)

Both ExecutorService and ListeningExecutorService can submit a Runnable and Callable parameter.

Submit a Callable:

public static void submitCallable() throws Exception{
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Callable<String> r = () -> {
        return "abcd";
    };
    Future<String> future = executorService.submit(r);
    System.out.println(future.get());
    executorService.shutdown();
}

Submit a Runnable :

public static void submitRunnable() throws Exception{
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Runnable r = () -> {
        System.out.println(1);
    };
    Future future = executorService.submit(r);
    System.out.println(future.get());   // future of submitting a runnable is always null
    executorService.shutdown();
}

 

Execute a Runnable:

public static void executeCallable() throws Exception{
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Runnable r = () -> {
        System.out.println("abcd");
    };
    executorService.execute(r);
    executorService.shutdown();
}

Code on git