SoFunction
Updated on 2025-03-02

Summary of the difference between Executor and Executors in Java

In Java concurrent programming,ExecutorandExecutorsare two closely related but different functions of classes or interfaces, both of which are related to thread pool management and task execution. Understanding the difference between these two is very important for the correct use of Java concurrency API.

1. Definition and function of Executor

1.1 Executor Interface

ExecutorIt is a core interface in the Java concurrency framework, which provides a mechanism to decouple the submission of tasks from the execution of tasks. in other words,ExecutorThe design goal of the interface is to abstract the behavior of "task execution", so that the task committer does not have to care about how the task is executed (such as whether it is executed in a new thread, whether it is executed in a certain thread pool, etc.).

public interface Executor {
    void execute(Runnable command);
}

execute(Runnable command)method:This isExecutorThe only method in the interface, it accepts an implementationRunnableInterface tasks and schedule execution of the task. How to perform this task in detail is implementedExecutorClass decision of interface.

1.2 The design purpose of the Executor interface

ExecutorThe main purpose of the interface is to simplify the execution of concurrent tasks, providing a unified way to submit tasks without the need for developers to explicitly create and manage threads. Through this interface, developers can separate task execution strategies (such as thread pools, asynchronous execution, etc.) from business logic, making the code more concise and maintainable.

2. Definition and function of Executors

2.1 Executors Class

Executorsis a utility class that contains some static factory methods for creatingExecutorExecutorServiceScheduledExecutorServiceCommonly used implementations of etc. These implementations are usually related to thread pools, soExecutorsClasses are very commonly used in actual development.

public class Executors {
    // Create a single threaded executor    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, ,
                                    new LinkedBlockingQueue<Runnable>()));
    }

    // Create a thread pool with fixed number of threads    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, ,
                                      new LinkedBlockingQueue<Runnable>());
    }

    // Create a thread pool that can be extended as needed    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, ,
                                      new SynchronousQueue<Runnable>());
    }

    // Other factory methods...}

2.2 Common methods of Executors class

ExecutorsThe class provides a variety of methods to create thread pools, and each method returns theExecutorServiceDifferent implementations of  , these implementations are suitable for different concurrency scenarios:

  • newFixedThreadPool(int nThreads): Create a fixed-size thread pool. The number of threads in this thread pool is fixed. No matter how many tasks are submitted to the thread pool, the number of threads running simultaneously in the thread pool will not exceed the specified size. Suitable for handling a stable number of concurrent tasks.

  • newCachedThreadPool(): Create a cacheable thread pool. This thread pool will create new threads as needed and will be recycled if the thread is idle for more than 60 seconds, so it is very useful in scenarios with a large number of short-term asynchronous tasks.

  • newSingleThreadExecutor(): Create a single threaded executor. This executor ensures that all tasks are executed sequentially in a single thread, and is suitable for scenarios where tasks need to be executed sequentially.

  • newScheduledThreadPool(int corePoolSize): Create a timed thread pool. This thread pool supports task scheduling and periodic execution, and is suitable for scenarios where tasks need to be executed regularly.

3. The difference between Executor and Executors

3.1 The difference between interface and tool classes

  • ExecutorIt's the interface:Executoris an interface that defines a standard method for task executionexecute(Runnable command). It provides an abstraction layer so that the task committer does not need to care about how the task is executed.

  • ExecutorsIt is a tool class:Executorsis a tool class that provides the creation of variousExecutorExecutorServiceImplemented static factory method. It simplifies the creation process of thread pools, allowing developers to easily obtain thread pool implementations suitable for their application scenarios.

3.2 Differences in concerns

  • ExecutorWhat is focused on is the execution of tasks:ExecutorFocus on how to execute submitted tasks and defines the standard interface for task execution. It is a behavioral norm, so that different executors can be replaced without changing the behavior of the code.

  • ExecutorsWhat is concerned about is how to createExecutorExecutorsThe focus is on how to create a thread pool or task executor that meets specific needs. It provides a variety of predefinedExecutorandExecutorServiceImplementation, help developers choose appropriate execution strategies based on different concurrency needs.

3.3 Differences in usage scenarios

  • ExecutorUse scenarios:ExecutorUsually used in scenarios where custom task execution logic is required, such as custom task scheduling policies, managing task queues, etc. Developers can implementExecutorInterface, define your own task executor.

  • ExecutorsUse scenarios:ExecutorsUsually used to create standard thread pools or executors, suitable for common concurrent task execution needs. By usingExecutorsThe factory method provided by developers can quickly create and use thread pools without caring about the underlying implementation details.

4. Examples in actual use

4.1 Using Executor

Suppose we have a simple task scheduling system that we can useExecutorThe interface to abstract the execution process of tasks:

public class SimpleExecutor implements Executor {
    @Override
    public void execute(Runnable command) {
        new Thread(command).start();
    }
}

thisSimpleExecutorClass has been implementedExecutorInterface, which creates a new thread to execute the task every time it receives it. This implementation is very simple, but in practical applications, more complex executors, such as thread pools, are often used.

4.2 Using Executors

passExecutorsTool class, we can easily create a fixed-size thread pool and submit tasks:

public class ExecutorExample {
    public static void main(String[] args) {
        ExecutorService executor = (5);

        for (int i = 0; i < 10; i++) {
            (new RunnableTask(i));
        }

        ();
    }
}

class RunnableTask implements Runnable {
    private int taskId;

    public RunnableTask(int id) {
         = id;
    }

    @Override
    public void run() {
        ("Executing task " + taskId + " by " + ().getName());
    }
}

In this example, we use(5)A thread pool with a fixed size of 5 was created, and then 10 tasks were submitted to the thread pool for execution. The thread pool will automatically manage the execution of these tasks and reuse threads to handle the tasks.

5. Summary

In Java concurrent programming,ExecutorandExecutorsAlthough the names are similar, they have very different responsibilities and uses:

  • ExecutorIt is an interface that defines the standard method of task execution, which is the core abstraction of task execution in concurrent programming.ExecutorLet the task submitter not care about the specific execution method of the task, thereby decoupling the task execution and business logic.

  • Executorsis a tool class that provides multiple factory methods to create different types ofExecutorandExecutorServiceaccomplish. By usingExecutorsProvided factory methods, developers can easily create and manage thread pools to suit various concurrent programming needs.

This is the end of this article about the difference between Executor and Executors in Java. For more related Java Executor Executors content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!