In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you what is the design concept of the executors framework in Java J.U.C. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
A brief introduction to the executors framework
Juc-executors framework is the most complex framework of class / interface relationship in the whole J.U.C package. The premise of really understanding executors framework is to sort out the relationship between each module. From the whole to the part, we can thoroughly understand the function of each module and the design ideas behind it.
There are too many articles on the Internet about the executors framework, either in general, or blind to Mount Tai, lack of an overall perspective, and many simply do not understand the design ideas and module relationships of the whole framework. This article will summarize the whole executors framework, introduce the functions and relationships of each module, and then discuss each module in depth, including the tool classes in the module.
Start with Executor
When Executor is JDK1.5, with the introduction of an interface by J.U.C, the main purpose of introducing this interface is to decouple the task itself and its execution. When we used to perform a task through a thread, we often need to create a thread and then call the thread's start method to execute the task:
New Thread (new (RunnableTask (). Start (); the above RunnableTask is a task class that implements the Runnable interface. The Executor interface decouples the task and task execution. There is only one method for this API. The input parameter is the task to be executed: public interface Executor {/ * executes a given Runnable task. * the specific implementation method varies according to the implementation of Executor. * * @ param command the runnable task * @ throws RejectedExecutionException if this task cannot be accepted for execution * @ throws NullPointerException if command is null * / void execute (Runnable command);}
We can perform tasks like this without worrying about thread creation:
Executor executor = someExecutor; / / create a specific Executor object executor.execute (new RunnableTask1 ()); executor.execute (new RunnableTask2 ());
Because Executor is only an interface, the specific ways to perform tasks vary depending on its implementation, such as:
① synchronous execution of tasks
Class DirectExecutor implements Executor {public void execute (Runnable r) {r.run ();}}
DirectExecutor is a synchronous task executor. For incoming tasks, execute will not return until the execution is complete.
② executes tasks asynchronously
/ * Fallback if ForkJoinPool.commonPool () cannot support parallelism * / static final class ThreadPerTaskExecutor implements Executor {public void execute (Runnable r) {new Thread (r) .start ();}}
ThreadPerTaskExecutor is an asynchronous task executor. For each task, the executor creates a new thread to execute the task.
Note: Java threads are mapped to threads of the local operating system one by one. When the Java thread starts, a local operating system thread is created; when the Java thread terminates, the corresponding operating system thread is recycled. Because CPU resources are limited, there is an upper limit on the number of threads, so thread pool is generally used to manage thread creation / recycling, and this approach is actually the embryonic form of thread pool.
③ queues tasks for execution.
Class SerialExecutor implements Executor {final Queue tasks = new ArrayDeque (); final Executor executor; Runnable active; SerialExecutor (Executor executor) {this.executor = executor;} public synchronized void execute (final Runnable r) {tasks.offer (new Runnable () {public void run () {try {r.run ();} finally {scheduleNext ();}) If (active = = null) {scheduleNext ();}} protected synchronized void scheduleNext () {if ((active = tasks.poll ())! = null) {executor.execute (active);}
SerialExecutor queues incoming tasks (in FIFO order) and then takes a task from the head of the queue to execute.
The above examples only show some possible Executor implementations, and many concrete implementation classes of Executor are provided in the J.U.C package. As we will talk about later, the key here is to understand the design idea of Executor-decoupling tasks and task execution.
Enhanced Executor--ExecutorService
The function provided by the Executor interface is very simple, and to enhance it, J.U.C provides another interface called ExecutorService. ExecutorService was also introduced with J.U.C when JDK1.5:
Public interface ExecutorService extends Executor
As you can see, ExecutorService inherits Executor, which enhances control over tasks on the basis of Executor, and includes the management of its own lifecycle. There are four main categories:
Close the executor and prohibit the submission of tasks
Monitor the status of the actuator
Provide support for asynchronous tasks
Provides support for batch tasks.
Public interface ExecutorService extends Executor {/ * close the actuator, the main features are as follows: * 1. Tasks that have been submitted to the executor will continue to be executed, but new task submissions will no longer be accepted; * 2. If the actuator has been turned off, there is no side effect to call again. * / void shutdown (); / * close the actuator immediately, which mainly has the following characteristics: * 1. If you try to stop all tasks that are in progress, there is no guarantee that you will stop successfully, but you will try your best (for example, tasks that are interrupted through Thread.interrupt, but tasks that do not respond to interruptions may not be terminated); * 2. Suspend processing of tasks that have been submitted but not executed; * * @ return returns a list of tasks that have been submitted but not executed * / List shutdownNow (); / * * returns true if the executor has been closed. * / boolean isShutdown (); / * determine whether the actuator has been terminated. *
* return true only if the actuator has been turned off and all tasks have been completed. * Note: unless shutdown or shutdownNow is called first, this method always returns false. * / boolean isTerminated (); / * blocks the calling thread and waits for the executor to reach the termination state. * * @ return {@ code true} if the executor finally reaches the termination state, return true; otherwise return false * @ throws InterruptedException if interrupted while waiting * / boolean awaitTermination (long timeout, TimeUnit unit) throws InterruptedException; / * to submit a task with a return value for execution. * Note: the get method of Future will return the return value of task on successful completion. * * @ param task Task to be submitted * @ param Task return value Type * @ return returns the Future object of the task * @ throws RejectedExecutionException if the task cannot be scheduled for execution * @ throws NullPointerException if the task is null * / Future submit (Callable task); / * submit a Runnable task for execution. * Note: the get method of Future will return the given result upon successful completion (specified when entering the parameter). * * @ param task Task to be submitted * result returned by @ param result * @ result Type returned by param * @ return returns the Future object of the task * @ throws RejectedExecutionException if the task cannot be scheduled for execution * @ throws NullPointerException if the task is null * / Future submit (Runnable task, T result) / * submit a Runnable task for execution. * Note: the get method of Future will return null. * * @ param task Task to be submitted * @ return returns the Future object of the task * @ throws RejectedExecutionException if the task cannot be scheduled to execute * @ throws NullPointerException if the task is null * / Future submit (Runnable task); / * executes all tasks in the given set, and returns the Future list that maintains the task status and results when all tasks are completed. *
* Note: this method is a synchronization method. Returns the Future.isDone () of all elements in the list as true. * * @ param tasks task collection * @ param task return result type * @ return task Future object list in the same order as the iterator in the collection. If the task is interrupted while waiting, * @ throws InterruptedException will cancel all outstanding tasks. * @ throws NullPointerException any task is null * @ throws RejectedExecutionException if any task cannot be scheduled for execution * / List invokeAll (Collection
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.