Java.util.concurrent.Executor interface with Examples

The concurrent API in Java provides a feature known as an executor that initiates and controls the execution of threads. As such, an executor offers an alternative to managing threads using the thread class. At the core of an executor is the Executor interface. It refers to the objects that execute submitted Runnable tasks.

Class heirarchy:

java.util.concurrent
  ↳ Interface Executor

Implementing Sub-Interfaces:

ExecutorService
ScheduledExecutorService

Implementing Classes:

AbstractExecutorService
ForkJoinPool
ScheduledThreadPoolExecutor
ThreadPoolExecutor

Methods in Executor interface:



  1. execute(): This function executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.

    Syntax:

    void execute(Runnable task)
    

Example to demonstrate an Executor.

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
  
public class ExecutorDemo {
    public static void main(String[] args)
    {
        ExecutorImp obj = new ExecutorImp();
        try {
            obj.execute(new NewThread());
        }
        catch (RejectedExecutionException
               | NullPointerException exception) {
            System.out.println(exception);
        }
    }
}
  
class ExecutorImp implements Executor {
    @Override
    public void execute(Runnable command)
    {
        new Thread(command).start();
    }
}
  
class NewThread implements Runnable {
    @Override
    public void run()
    {
        System.out.println("Thread executed under an executor");
    }
}

chevron_right


Output:

Thread executed under an executor

Reference:https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Executor.html

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.