In Java concurrent programming,Executor
andExecutors
are 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
Executor
It 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,Executor
The 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 isExecutor
The only method in the interface, it accepts an implementationRunnable
Interface tasks and schedule execution of the task. How to perform this task in detail is implementedExecutor
Class decision of interface.
1.2 The design purpose of the Executor interface
Executor
The 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
Executors
is a utility class that contains some static factory methods for creatingExecutor
、ExecutorService
、ScheduledExecutorService
Commonly used implementations of etc. These implementations are usually related to thread pools, soExecutors
Classes 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
Executors
The class provides a variety of methods to create thread pools, and each method returns theExecutorService
Different 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
Executor
It's the interface:Executor
is 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.Executors
It is a tool class:Executors
is a tool class that provides the creation of variousExecutor
、ExecutorService
Implemented 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
Executor
What is focused on is the execution of tasks:Executor
Focus 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.Executors
What is concerned about is how to createExecutor
:Executors
The focus is on how to create a thread pool or task executor that meets specific needs. It provides a variety of predefinedExecutor
andExecutorService
Implementation, help developers choose appropriate execution strategies based on different concurrency needs.
3.3 Differences in usage scenarios
Executor
Use scenarios:Executor
Usually used in scenarios where custom task execution logic is required, such as custom task scheduling policies, managing task queues, etc. Developers can implementExecutor
Interface, define your own task executor.Executors
Use scenarios:Executors
Usually used to create standard thread pools or executors, suitable for common concurrent task execution needs. By usingExecutors
The 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 useExecutor
The interface to abstract the execution process of tasks:
public class SimpleExecutor implements Executor { @Override public void execute(Runnable command) { new Thread(command).start(); } }
thisSimpleExecutor
Class has been implementedExecutor
Interface, 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
passExecutors
Tool 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,Executor
andExecutors
Although the names are similar, they have very different responsibilities and uses:
Executor
It is an interface that defines the standard method of task execution, which is the core abstraction of task execution in concurrent programming.Executor
Let the task submitter not care about the specific execution method of the task, thereby decoupling the task execution and business logic.Executors
is a tool class that provides multiple factory methods to create different types ofExecutor
andExecutorService
accomplish. By usingExecutors
Provided 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!