In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the common thread pools". In the daily operation, I believe that many people have doubts about the common thread pools. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what are the common thread pools?" Next, please follow the editor to study!
One: several common thread pools 1.1 FixedThreadPool
The FixedThreadPool thread pool has the same number of core threads as the maximum number of threads, so it can be thought of as a thread pool with a fixed number of threads.
The characteristic is: except that the number of threads in the thread pool needs to increase from 0 in the initial stage, the number of threads after that is fixed. Even if the number of tasks exceeds the number of threads, the thread pool will not create more threads to handle tasks. Instead, tasks that exceed the processing capacity of threads will be placed in the task queue to wait. And even if the task queue is full, when it is time to continue to increase the number of threads, because its maximum number of threads is the same as the number of core threads, it is impossible to add new threads.
As shown in the figure, there are 10 threads in the thread pool, which will execute tasks incessantly. If a thread task is finished, it will get new tasks from the task queue and continue to execute. During this period, the number of threads will not increase or decrease, and will always be kept at 10.
1.2 CachedThreadPool
CachedThreadPool, which can be called cacheable thread pool, is characterized by the fact that the number of threads can be increased almost indefinitely (the actual maximum can reach Integer.MAX_VALUE, which is 2 ^ 31-1), and threads can be reclaimed when they are idle.
CachedThreadPool thread pool it also has a queue to store submitted tasks, but this queue is SynchronousQueue, the capacity of the queue is 0, it does not actually store any tasks, it is only responsible for the transfer and delivery of tasks, so it is more efficient.
When a task is submitted, the thread pool determines whether there are idle threads in the created thread, if there are idle threads, assigns the task directly to the idle thread, and if there is no idle thread, the new thread executes the task. in this way, you can add new threads dynamically. As shown in the code below.
/ * * @ date 23:17 on 2020-11-15 * * @ discription cached thread pool * / public class CachedThreadPool {public static void main (String [] args) {ExecutorService service = Executors.newCachedThreadPool (); for (int I = 0; I < 1000; iSuppli +) {service.execute (new ThreadPoolDemo.Task ()) }} static class Task implements Runnable {@ Override public void run () {System.out.println ("Thread Name:" + Thread.currentThread () .getName ());}
Because the task execution is simple, before the for loop commit task ends, it may cause the first task to be executed and the thread idle to execute the later task, so that there will be no thread named pool-1-thread-1000.
Assuming that the processing time of these tasks is very long, because the operation of the for loop to submit the task is very fast, but it is time-consuming to execute the task, it may result in 1000 tasks being submitted, but the first task has not yet been executed, so CachedThreadPool can dynamically scale the number of threads. As the task is submitted, it constantly creates 1000 threads to execute the task, and when the task is executed, it can dynamically scale the number of threads. Assuming that there are no new tasks, then a large number of idle threads will cause a waste of memory resources, and the thread pool will detect whether the thread has a task to execute within 60 seconds, if not, it will be destroyed, and the number of threads will eventually be reduced to 0.
1.3 ScheduledThreadPool
Thread pool ScheduledThreadPool, which supports the execution of tasks at regular or periodic intervals.
For example, a task is executed every 10 seconds, and there are three main ways to achieve this function, as shown in the code:
/ * * @ date 23:34 on 2020-11-15 * * @ discription supports thread pools for scheduled or periodic task execution * / public class ScheduledThreadPool {public static void main (String [] args) {ScheduledExecutorService service = Executors.newScheduledThreadPool (10) / * schedule-simply means to delay the execution of a task after a specified time, * if the parameter in the code is set to 10 seconds, that is, the task ends after 10 seconds. * / service.schedule (new ThreadPoolDemo.Task (), 10, TimeUnit.SECONDS); / * scheduleAtFixedRate-indicates that the task is executed at a fixed frequency, * its second parameter initialDelay represents the first delay time, and * the third parameter period represents the period, that is, how long each task is delayed after the first delay. * / service.scheduleAtFixedRate (new ThreadPoolDemo.Task (), 10, 10, TimeUnit.SECONDS) / * scheduleWithFixedDelay-similar to the second method, it also executes tasks periodically, but the difference lies in the definition of cycle. * the previous scheduleAtFixedRate starts with the time when the task starts, and the second task starts when the time comes, no matter how long it takes to execute the task. * the scheduleWithFixedDelay method starts timing with the end of the task as the time starting point of the next cycle. * / service.scheduleWithFixedDelay (new ThreadPoolDemo.Task (), 10,10, TimeUnit.SECONDS);}}
For example, suppose a student is staying up late to write code and needs coffee to refresh himself. Suppose it takes 10 minutes to drink coffee each time. If the second method scheduleAtFixedRate is used at this time, and the interval is set to 1 hour, then he will drink a cup of coffee at every hour. Here is the schedule:
00:00: start drinking coffee
00:10: finished.
01:00: start drinking coffee
01:10: finished.
02:00: start drinking coffee
02:10: finished.
Using the third method, scheduleWithFixedDelay, and the interval is also set to 1 hour, since each cup of coffee takes 10 minutes, and scheduleWithFixedDelay starts with the time when the task is completed, the time for the second coffee will be at 1:10 instead of 1:00 sharp. Here is the schedule:
00:00: start drinking coffee
00:10: finished.
01:10: start drinking coffee
01:20: finished.
02:20: start drinking coffee
02:30: finished.
1.4 SingleThreadExecutor
SingleThreadExecutor, which uses a unique thread to execute the task, is the same as FixedThreadPool, except that there is only one thread, and if an exception occurs during the execution of the task, the thread pool will recreate a thread to perform subsequent tasks.
Because there is only one thread, this thread pool is very suitable for scenarios where all tasks need to be executed in the order in which they are submitted, and the first few thread pools do not necessarily guarantee that the order in which tasks are executed is equal to the order in which they are committed. because they are executed in parallel with multiple threads.
1.5 SingleThreadScheduledExecutor
SingleThreadScheduledExecutor, which is actually very similar to the third type of ScheduledThreadPool thread pool, is just a special case of ScheduledThreadPool with only one thread inside.
Note: it simply sets the number of core threads in ScheduledThreadPool to 1, that is, new ScheduledThreadPoolExecutor (1), which does not mean that the largest thread is one.
1.6 Summary
2: add thread pool ForkJoinPool to JDK1.7
ForkJoinPool, this thread pool is added in JDK 7, the main usage is the same as the previous thread pool, and the task is handed over to the thread pool to execute, and there is also a task queue in the thread pool to store tasks. ForkJoinPool is very suitable for recursive scenarios, such as tree traversal, optimal path search, and so on.
There are two very big differences between the ForkJoinPool thread pool and the previous thread pool.
The first point is that it is very suitable for performing tasks that produce subtasks.
For example, we have a Task, which can generate three sub-tasks. After the three sub-tasks are executed in parallel, the results are summarized to the Result. For example, if the main task needs to perform very heavy computing tasks, we can split the calculation into three parts, which are independent of each other. In this way, we can take advantage of the multi-core advantages of CPU, parallel computing, and then summarize the results. There are two main steps involved, the first step is to split the Fork, and the second step is to summarize the Join, which is the origin of the name of the ForkJoinPool thread pool.
The ForkJoinPool thread pool has several ways to split and summarize tasks, one of which calculates the Fibonacci sequence as shown in the code below.
/ * * @ date 0:06 on 2020-11-16 * * @ discription ForkJoinPool calculates the Fibonacci series * prints out the values of terms 0 to 9 of the Fibonacci series: * / public class Fibonacci extends RecursiveTask {int n; public Fibonacci (int n) {this.n = n;} @ Override protected Integer compute () {if (n)
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.