Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
runnable

How to execute a runnable in the executor service

abhilash

Overview

The submit() method is used to execute a runnable in the executor service.

Note: Refer to What is the difference between runnable and callable in Java? to understand more about runnables in Java.

Syntax

Future<?> submit(Runnable task)
Syntax

Parameters

  • Runnable task: The runnable task to execute.

Return value

The method returns a Future.

null is stored as the future’s value or result upon successful completion of the task.

Code

import java.util.concurrent.*;

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Runnable runnable = () -> System.out.println("Callable called");

        Future<?> runnableFuture = executorService.submit(runnable);

        System.out.println("Result of the Future - " + runnableFuture.get());

        executorService.shutdown();

    }
}
Implementation of the submit() method

Explanation

  • Line 1: We import the relevant packages.
  • Line 6: We define a single-threaded executor service called executorService.
  • Line 8: We define a Runnable called runnable that prints a string.
  • Line 10: We submit the runnable to the executorService using the submit() method. The submit() method returns a future.
  • Line 12: We retrieve the value of the Future obtained in line 10 using the get() method and print the result.

RELATED TAGS

java
communitycreator
runnable
RELATED COURSES

View all Courses

Keep Exploring