Интерфейс Java.util.concurrent.Executor с примерами

Опубликовано: 7 Февраля, 2022

Параллельный API в Java предоставляет функцию, известную как исполнитель, который инициирует и контролирует выполнение потоков . Таким образом, исполнитель предлагает альтернативу управлению потоками с помощью класса потока. В основе исполнителя лежит интерфейс исполнителя. Он относится к объектам, которые выполняют отправленные задачи Runnable.

Иерархия классов:

java.util.concurrent
  ↳ Исполнитель интерфейса

Реализация субинтерфейсов:

ExecutorService
ScheduledExecutorService

Реализация классов:

AbstractExecutorService
ForkJoinPool
ScheduledThreadPoolExecutor
ThreadPoolExecutor

Методы в интерфейсе Executor:

  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.

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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.