In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the ways to create a thread pool". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "what are the ways to create a thread pool"?
What is a thread pool?
Thread pool (ThreadPool) is a mechanism that manages and uses threads based on pooling ideas. It stores multiple threads in a "pool" in advance, and when there are tasks, you can avoid the performance overhead caused by recreating and destroying threads. You only need to take the corresponding threads from the "pool" to execute the corresponding tasks.
Pooling ideas are also widely used in computers, such as the following:
Memory pool (Memory Pooling): apply for memory in advance, improve the speed of applied memory, and reduce memory fragmentation.
Connection pool (Connection Pooling): apply for database connections in advance to improve the speed of applying for connections and reduce the overhead of the system.
Instance pool (Object Pooling): recycle objects to reduce the expensive consumption of resources during initialization and release.
The advantages of thread pools are mainly reflected in the following four points:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Reduce resource consumption: reuse created threads through pooling technology to reduce the loss caused by thread creation and destruction.
Improve response time: when a task arrives, it can be executed without waiting for the thread to be created.
Improve the manageability of threads: threads are scarce resources. if they are created without restriction, it will not only consume system resources, but also lead to resource scheduling imbalance and reduce the stability of the system because of the unreasonable distribution of threads. Thread pools can be used for unified allocation, tuning, and monitoring.
Provide more and more powerful features: thread pools are extensible, allowing developers to add more functionality to them. For example, the delayed timed thread pool ScheduledThreadPoolExecutor allows tasks to be deferred or executed on a regular basis.
At the same time, Alibaba also stipulated in his "Java Development Manual" that thread resources must be provided through the thread pool, and it is not allowed to explicitly create threads in the application.
Note: the advantage of thread pool is to reduce the time spent on creating and destroying threads and the overhead of system resources, and to solve the problem of insufficient resources. If you do not use thread pools, it is possible for the system to create a large number of similar threads, resulting in running out of memory or "excessive switching".
Now that we know what a thread pool is and why we use a thread pool, let's look at how to use a thread pool.
Thread pool usage
There are seven ways to create thread pools, but in general they can be divided into two categories:
One is the thread pool created by ThreadPoolExecutor.
Another class is the thread pool created through Executors.
There are a total of seven ways to create a thread pool (of which 6 are created through Executors and 1 is created through ThreadPoolExecutor):
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Executors.newFixedThreadPool: create a fixed size thread pool to control the number of concurrent threads, and excess threads will wait in the queue
Executors.newCachedThreadPool: create a cacheable thread pool. If the number of threads exceeds the number required for processing, the cache will be reclaimed after a period of time. If the number of threads is not enough, create a new thread.
Executors.newSingleThreadExecutor: create a thread pool with a single thread, which ensures the first-in-first-out execution order
Executors.newScheduledThreadPool: create a thread pool that can perform deferred tasks
Executors.newSingleThreadScheduledExecutor: create a single-threaded thread pool that can perform deferred tasks
Executors.newWorkStealingPool: create a thread pool for preemptive execution (tasks are executed in uncertain order) [JDK 1.8 added].
ThreadPoolExecutor: the original way to create a thread pool, which contains seven parameters to set, which will be discussed in more detail later.
The significance of a single-thread pool you can see from the above code that both newSingleThreadExecutor and newSingleThreadScheduledExecutor create a single-thread pool, so what is the meaning of a single-thread pool? A: although it is a single thread pool, it provides functions such as work queue, life cycle management, worker thread maintenance and so on.
Next, let's look at the specific use of each thread pool creation.
1.FixedThreadPool
Create a fixed-size thread pool that controls the number of concurrent threads, and excess threads wait in the queue.
Examples of use are as follows:
Public static void fixedThreadPool () {/ / create 2 data-level thread pools ExecutorService threadPool = Executors.newFixedThreadPool (2); / / create task Runnable runnable = new Runnable () {@ Override public void run () {System.out.println ("tasks are executed, threads:" + Thread.currentThread (). GetName ());}} / / Thread pool executes tasks (adding 4 tasks at a time) / / there are two ways to execute tasks: submit and execute threadPool.submit (runnable); / / execution mode 1:submit threadPool.execute (runnable); / / execution mode 2:execute threadPool.execute (runnable); threadPool.execute (runnable);}
The implementation results are as follows:
If you find the above methods cumbersome, use a simpler method, as shown in the following code:
Public static void fixedThreadPool () {/ / create thread pool ExecutorService threadPool = Executors.newFixedThreadPool (2); / / execute task threadPool.execute (()-> {System.out.println ("task is executed, thread:" + Thread.currentThread (). GetName ());});}
2.CachedThreadPool
Create a cacheable thread pool. If the number of threads exceeds the processing requirement, the cache will be reclaimed after a period of time. If the number of threads is not enough, create a new thread.
Examples of use are as follows:
Public static void cachedThreadPool () {/ / create thread pool ExecutorService threadPool = Executors.newCachedThreadPool (); / / execute task for (int I = 0; I
< 10; i++) { threadPool.execute(() ->{System.out.println ("tasks are executed, threads:" + Thread.currentThread (). GetName ()); try {TimeUnit.SECONDS.sleep (1);} catch (InterruptedException e) {});}}
The implementation results are as follows:
As can be seen from the above results, the thread pool creates 10 threads to perform the corresponding tasks.
3.SingleThreadExecutor
Create a thread pool with a single number of threads, which ensures the order of first-in, first-out execution.
Examples of use are as follows:
Public static void singleThreadExecutor () {/ / create thread pool ExecutorService threadPool = Executors.newSingleThreadExecutor (); / / execute task for (int I = 0; I
< 10; i++) { final int index = i; threadPool.execute(() ->{System.out.println (index + ": task executed"); try {TimeUnit.SECONDS.sleep (1);} catch (InterruptedException e) {}});}}
The implementation results are as follows:
4.ScheduledThreadPool
Create a thread pool that can perform deferred tasks.
Examples of use are as follows:
Public static void scheduledThreadPool () {/ / create thread pool ScheduledExecutorService threadPool = Executors.newScheduledThreadPool (5); / / add scheduled execution tasks (execute after 1s) System.out.println ("add tasks, time:" + new Date ()); threadPool.schedule (()-> {System.out.println ("tasks are executed, time:" + new Date () Try {TimeUnit.SECONDS.sleep (1);} catch (InterruptedException e) {}, 1, TimeUnit.SECONDS);}
The implementation results are as follows:
As can be seen from the above results, the task was executed after 1 second, which is in line with our expectations.
5.SingleThreadScheduledExecutor
Create a single-threaded thread pool that can perform deferred tasks.
Examples of use are as follows:
Public static void SingleThreadScheduledExecutor () {/ / create thread pool ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor (); / / add scheduled execution tasks (execute after 2s) System.out.println ("add tasks, time:" + new Date ()); threadPool.schedule (()-> {System.out.println ("tasks are executed, time:" + new Date () Try {TimeUnit.SECONDS.sleep (1);} catch (InterruptedException e) {}, 2, TimeUnit.SECONDS);}
The implementation results are as follows:
As can be seen from the above results, the task was executed 2 seconds later, in line with our expectations.
6.newWorkStealingPool
Create a thread pool for preemptive execution (the order in which tasks are executed is uncertain). Note that this method can only be used in JDK version 1.8 +.
Examples of use are as follows:
Public static void workStealingPool () {/ / create thread pool ExecutorService threadPool = Executors.newWorkStealingPool (); / / execute task for (int I = 0; I
< 10; i++) { final int index = i; threadPool.execute(() ->{System.out.println (index + "is executed, thread name:" + Thread.currentThread () .getName ());});} / / ensure that the task execution completes while (! threadPool.isTerminated ()) {}}
The implementation results are as follows:
As can be seen from the above results, the order in which the tasks are executed is uncertain because it is preemptive.
7.ThreadPoolExecutor
The original way to create a thread pool, which contains seven parameters to set.
Examples of use are as follows:
Public static void myThreadPoolExecutor () {/ / create thread pool ThreadPoolExecutor threadPool = new ThreadPoolExecutor (5,10,100, TimeUnit.SECONDS, new LinkedBlockingQueue (10)); / / execute task for (int I = 0; I
< 10; i++) { final int index = i; threadPool.execute(() ->{System.out.println (index + "is executed, thread name:" + Thread.currentThread () .getName ()); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();}});}}
The implementation results are as follows:
Introduction of ThreadPoolExecutor parameters
ThreadPoolExecutor can set up to 7 parameters, as shown in the following code:
Public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {/ / omit.}
The seven parameters represent the following meanings:
Parameter 1:corePoolSize
The number of core threads, the number of threads that are always alive in the thread pool.
Parameter 2:maximumPoolSize
Maximum number of threads, the maximum number of threads allowed in the thread pool, and the maximum number of threads that can be created when the task queue of the thread pool is full.
Parameter 3:keepAliveTime
The maximum number of threads can survive, when there is no task execution in the thread, the maximum thread will destroy some of the threads, and finally maintain the number of core threads.
Parameter 4:unit:
The unit is used in conjunction with the survival time of parameter 3, and is used to set the survival time of the thread. The time units of the parameter keepAliveTime can be selected as follows:
TimeUnit.DAYS: God
TimeUnit.HOURS: hour
TimeUnit.MINUTES: points
TimeUnit.SECONDS: seconds
TimeUnit.MILLISECONDS: millisecond
TimeUnit.MICROSECONDS: subtle
TimeUnit.NANOSECONDS: nanosecond
Parameter 5:workQueue
A blocking queue, which stores tasks waiting for execution in the thread pool, is thread-safe and contains the following seven types:
ArrayBlockingQueue: a bounded blocking queue consisting of array structures.
LinkedBlockingQueue: a bounded blocking queue consisting of linked list structures.
SynchronousQueue: a blocking queue that does not store elements, that is, it is submitted directly to the thread without holding them.
PriorityBlockingQueue: an unbounded blocking queue that supports prioritization.
DelayQueue: an unbounded blocking queue implemented using a priority queue from which elements can be extracted only when the delay expires.
LinkedTransferQueue: an unbounded blocking queue consisting of linked list structures. Similar to SynchronousQueue, there are also non-blocking methods.
LinkedBlockingDeque: a bidirectional blocking queue consisting of linked list structures.
The more common ones are LinkedBlockingQueue and Synchronous, and the queuing policy of the thread pool is related to BlockingQueue.
Parameter 6:threadFactory
Thread factory, which is mainly used to create threads, defaults to normal priority, non-daemon threads.
Parameter 7:handler
Reject policy, reject policy when processing a task, the system provides four options:
AbortPolicy: reject and throw an exception.
CallerRunsPolicy: use the currently called thread to perform this task.
DiscardOldestPolicy: discard a task at the queue header (oldest) and execute the current task.
DiscardPolicy: ignore and discard the current task.
The default policy is AbortPolicy.
Execution flow of thread pool
The execution process of ThreadPoolExecutor key nodes is as follows:
Create threads when the number of threads is less than the number of core threads.
When the number of threads is greater than or equal to the number of core threads, and the task queue is not full, put the task into the task queue.
When the number of threads is greater than or equal to the number of core threads, and the task queue is full: if the number of threads is less than the maximum number of threads, create a thread; if the number of threads is equal to the maximum number of threads, throw an exception and reject the task.
The execution flow of the thread pool is shown in the following figure:
Thread reject policy
Let's demonstrate the trigger of ThreadPoolExecutor's reject policy. We use DiscardPolicy's reject policy, which ignores and discards the policy of the current task. The implementation code is as follows:
Public static void main (String [] args) {/ / the specific method of the task Runnable runnable = new Runnable () {@ Override public void run () {System.out.println ("current task is executed, execution time:" + new Date () + "thread of execution:" + Thread.currentThread () .getName ()) Try {/ / wait for 1s TimeUnit.SECONDS.sleep (1);} catch (InterruptedException e) {e.printStackTrace ();} / / create a thread whose task queue length is 1 ThreadPoolExecutor threadPool = new ThreadPoolExecutor (1,1,100, TimeUnit.SECONDS, new LinkedBlockingQueue (1), new ThreadPoolExecutor.DiscardPolicy ()) / / add and execute 4 tasks: threadPool.execute (runnable);}
We create a thread pool with both the core thread number and the maximum thread number of 1, and set the task queue of the thread pool to 1, so that when we have more than 2 tasks, the reject policy is triggered. The result of the execution is shown below:
From the above results, we can see that only two tasks are executed correctly, while the other redundant tasks are abandoned and ignored. The use of other rejection strategies is similar, so I won't repeat them here.
Custom reject Policy
In addition to the four rejection policies provided by Java itself, we can also customize the rejection policy. The sample code is as follows:
Public static void main (String [] args) {/ / the specific method of the task Runnable runnable = new Runnable () {@ Override public void run () {System.out.println ("current task is executed, execution time:" + new Date () + "thread of execution:" + Thread.currentThread () .getName ()) Try {/ / wait for 1s TimeUnit.SECONDS.sleep (1);} catch (InterruptedException e) {e.printStackTrace ();} / / create a thread whose task queue length is 1 ThreadPoolExecutor threadPool = new ThreadPoolExecutor (1,1,100, TimeUnit.SECONDS, new LinkedBlockingQueue (1)) New RejectedExecutionHandler () {@ Override public void rejectedExecution (Runnable r) ThreadPoolExecutor executor) {/ / execute actions related to custom reject policy System.out.println ("I am a custom reject policy ~") }}); / / add and execute 4 tasks threadPool.execute (runnable);}
The execution result of the program is as follows:
What kind of thread pool do you choose?
After the above study, we also have a certain understanding of the whole thread pool, so how to choose the thread pool?
Let's take a look at the answer given to us by Alibaba's "Java Development Manual":
[mandatory] Thread pool is not allowed to be created using Executors, but through ThreadPoolExecutor, which allows students to know more about the running rules of thread pool and avoid the risk of resource exhaustion.
Note: the disadvantages of the thread pool object returned by Executors are as follows:
1) FixedThreadPool and SingleThreadPool: the allowed request queue length is Integer.MAX_VALUE, which may pile up a large number of requests, resulting in OOM.
2) CachedThreadPool: the number of creation threads allowed is Integer.MAX_VALUE, which may create a large number of threads, resulting in OOM.
Therefore, to sum up, we recommend using ThreadPoolExecutor to create a thread pool, because this creation method is more controllable and more clear about the running rules of the thread pool, which can avoid some unknown risks.
Thank you for your reading. The above is the content of "what is the way to create a thread pool?" after the study of this article, I believe you have a deeper understanding of how to create a thread pool. Specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.