Thursday, September 25, 2025
HomeLanguagesJavaJava.util.concurrent.Executor interface with Examples

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 hierarchy: 

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. 

Java




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");
    }
}


Output: 

Thread executed under an executor

 

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

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32319 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6681 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6794 POSTS0 COMMENTS
Ted Musemwa
7070 POSTS0 COMMENTS
Thapelo Manthata
6753 POSTS0 COMMENTS
Umr Jansen
6761 POSTS0 COMMENTS