Explain the function of thread pool and how to use it in Java

itread01 2021-01-14 14:12:16
explain function thread pool use


![](https://img2020.cnblogs.com/other/1815316/202101/1815316-20210114083352253-122112091.png) Server applications ( Such as database and Web Server ) Need to handle high concurrency from the client 、 Less time consuming request tasks , So it is a very resource consuming operation to set up threads frequently to handle these requests . The normal approach is to create a new thread for a new request , Although this approach seems easy to implement , But it has major drawbacks . It takes more time to create a new thread for each request , More system resources are spent creating and destroying threads . So creating too many threads at the same time JVM It may cause the system to run out of memory , This requires limiting the number of threads to be created , That is, you need to use the thread pool .## One 、 What is Java Thread pool in ?** Thread pool technology is the reuse technology of threads , Use the previously created thread to execute the current task , It also provides a solution to the problem of thread cycle cost and resource conflict .** Because the thread already exists when the request arrives , Therefore, the delay caused by thread creation process is eliminated , Make the application more responsive .* Java Provided by **Executor** Interfaces and their sub interfaces **ExecutorService** and **ThreadPoolExecutor** As the center of the actuator framework . By using Executor, To complete a thread task, just implement Runnable Interface and give it to the actuator to execute .* Encapsulate the thread pool for you , Focus your programming tasks on the implementation of specific tasks , Rather than the implementation mechanism of threads .* To use thread pools , Let's first build a ExecutorService thing , And then pass it a set of tasks .ThreadPoolExcutor Class can set thread pool initialization and maximum thread capacity . ![](https://img2020.cnblogs.com/other/1815316/202101/1815316-20210114083352544-565106167.png) The figure above shows that thread pool initialization has 3 A thread , There is... In the task queue 5 A task object to be executed . ** Executor thread pool method **| Method | describe ||---|---||newFixedThreadPool(int) | Create a thread pool with a fixed number of threads ,int The argument represents the number of threads in the thread pool ||newCachedThreadPool() | Create a cacheable thread pool , This thread pool can flexibly recycle idle threads . If there are no idle threads , Then create a new thread to process the task .||newSingleThreadExecutor() | Create a single threaded thread pool , It will only use the only working thread to perform tasks ||newScheduledThreadPool| Create a fixed length thread pool , Support regular and periodic task execution | In the case of fixed thread pools , If all threads currently being executed by the actuator , Then the suspended task will be placed in the queue , And when the thread becomes idle .## Two 、 The thread pool example is in the following , We'll show you about thread pool executor Actuators .** Steps to follow in establishing thread pool processing tasks **1. Create a task object ( Realize Runnable Interface ), Used to perform specific task logic 2. Use Executors Set up a thread pool ExecutorService3. Give the task object to be executed to ExecutorService Do task processing 4. Stop Executor Thread pool ~~~// First step : Create a task object ( Realize Runnable Interface ), Used to perform specific task logic (Step 1) class Task implements Runnable { private String name; public Task(String s) { name = s; } // Print the task name and Sleep 1 second // The whole process is executed 5 Time public void run() { try{ for (int i = 0; i<=5; i++) { if (i==0) { Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); System.out.println(" Task initialization " + name +" = " + ft.format(d)); // The first time , Print the name and initialization time of each task } else{ Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); System.out.println(" The mission is in progress " + name +" = " + ft.format(d)); // Print the execution time of each task } Thread.sleep(1000); } System.out.println(" Task execution completed " + name); } catch(InterruptedException e) { e.printStackTrace(); } }}~~~ Test cases ~~~public class ThreadPoolTest { // The maximum number of threads in the thread pool static final int MAX_SIZE = 3; public static void main (String[] args) { // establish 5 A mission Runnable r1 = new Task("task 1"); Runnable r2 = new Task("task 2"); Runnable r3 = new Task("task 3"); Runnable r4 = new Task("task 4"); Runnable r5 = new Task("task 5"); // The second step : Create a thread pool with a fixed number of threads , The number of threads is MAX_SIZE ExecutorService pool = Executors.newFixedThreadPool(MAX_SIZE); // The third step : Give the task object to be executed to ExecutorService Do task processing pool.execute(r1); pool.execute(r2); pool.execute(r3); pool.execute(r4); pool.execute(r5); // Step four : Close thread pool pool.shutdown(); }} ~~~** Example execution results **~~~ Task initialization task 1 = 05:25:55 Task initialization task 2 = 05:25:55 Task initialization task 3 = 05:25:55 The mission is in progress task 3 = 05:25:56 The mission is in progress task 1 = 05:25:56 The mission is in progress task 2 = 05:25:56 The mission is in progress task 1 = 05:25:57 The mission is in progress task 3 = 05:25:57 The mission is in progress task 2 = 05:25:57 The mission is in progress task 3 = 05:25:58 The mission is in progress task 1 = 05:25:58 The mission is in progress task 2 = 05:25:58 The mission is in progress task 2 = 05:25:59 The mission is in progress task 3 = 05:25:59 The mission is in progress task 1 = 05:25:59 The mission is in progress task 1 = 05:26:00 The mission is in progress task 2 = 05:26:00 The mission is in progress task 3 = 05:26:00 Task execution completed task 3 Task execution completed task 2 Task execution completed task 1 Task initialization task 5 = 05:26:01 Task initialization task 4 = 05:26:01 The mission is in progress task 4 = 05:26:02 The mission is in progress task 5 = 05:26:02 The mission is in progress task 4 = 05:26:03 The mission is in progress task 5 = 05:26:03 The mission is in progress task 5 = 05:26:04 The mission is in progress task 4 = 05:26:04 The mission is in progress task 4 = 05:26:05 The mission is in progress task 5 = 05:26:05 The mission is in progress task 4 = 05:26:06 The mission is in progress task 5 = 05:26:06 Task execution completed task 4 Task execution completed task 5~~~ As shown in the program run result , Mission 4 Or mission 5 Only if the thread in the pool becomes idle . Before that , Additional tasks will be placed in the queue to be executed .![](https://img2020.cnblogs.com/other/1815316/202101/1815316-20210114083352791-1397971803.png) The thread pool performs the first three tasks , After the threads in the thread pool are reclaimed and empty, the task is processed 4 and 5![](https://img2020.cnblogs.com/other/1815316/202101/1815316-20210114083353083-354959744.png) One of the main advantages of using this thread pool approach is , If you want to deal with it once 10000 A request , But I don't want to build 10000 A thread , So as to avoid the downtime caused by the excessive use of system resources . You can use this method to create a system that contains 500 Thread pool of threads , And can submit to the thread pool 500 A request .ThreadPool At this point, the most 500 A thread , One time processing 500 A request . After the program of any thread is completed ,ThreadPool It's going to be the second one inside 501 Requests are assigned to the thread , And will continue to do the same for all remaining requests .** In the case of tight system resources , Thread pool is an effective solution to ensure the stable running of programs .**## 3、 ... and 、 Considerations and tuning for using thread pools 1. ** Deadlock :** Although deadlocks can occur in any multithreaded program , But thread pools introduce another Deadlock Case , Where all threads are waiting for the result of a blocking thread in the queue , Causes the thread to fail to continue .2. ** Thread leaks :** If a thread in the thread pool does not return correctly when the task completes , Thread leakage will occur . for example , A thread threw an exception and the pool class did not catch it , The thread exits abnormally , Thus, the size of the thread pool will be reduced by one . If this is repeated many times , Then the thread pool will eventually become empty , There are no threads available to perform other tasks .3. ** Threads rotate frequently :** If the thread pool size is very large , A lot of time is wasted in context switching between threads . So if system resources allow , It's not that the bigger the thread pool, the better .** Thread pool size optimization **: The optimal size of the thread pool depends on the number of processors available and the nature of the tasks to be processed . For CPU Intensive tasks , Suppose the system has N A logic processing core ,N or N+1 The size of the maximum number of thread pools for maximum efficiency . For I/O Intensive tasks , The waiting time of the request needs to be considered (W) And service processing time (S) The proportion of , The maximum size of the thread pool is N*(1+ W/S) Will achieve the highest efficiency . Don't dogmatically use the above summary , You need to set and tune flexibly according to your own application task processing types , One of them is the test experiment .## Welcome to my blog , There are a lot of excellent collections in it * This article is reprinted with reference to ( It has to be wired , You can't just turn text ):[ Alphabet blog ](http://www.zimug.com).** If you think it will help you , Give me some compliments 、 Share ! Your support is my inexhaustible creative power !** . in addition , The author recently output the following excellent content , Looking forward to your attention . * [《 Touch your hands and teach you to learn Spring Boot2.0》]( https://www.kancloud.cn/hanxt/springboot2/content )* [《Spring Security-JWT-OAuth2 A passbook 》](https://www.kancloud.cn/hanxt/springsecurity/content)* [《 Before and after the actual combat separation RBAC License management system 》](https://www.kancloud.cn/hanxt/vue-spring/content)* [《 Actual combat SpringCloud From bronze to King 》](https://www.kancloud.cn/hanxt/springcloud/content)* [《VUE Series in simple terms 》](https://www.kancloud.cn/hanxt/vuejs2/
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210114114646589t.html

  1. Spring boot static resource configuration principle (step by step source analysis, detailed and easy to understand)
  2. 400万Docker镜像中,51%的镜像存在高危漏洞
  3. Head first design pattern -- 10. Iterator pattern
  4. A few pictures, take down the HTTPS
  5. Simple use of pyecharts module
  6. [azure redis cache] discussion on the functionality of azure redis
  7. Installation of SVN under Linux
  8. Sorting out knowledge points of MySQL Cluster
  9. rocketmq-cpp-client Visual Studio 2019 编译
  10. rocketmq-cpp-client Visual Studio 2019 编译
  11. RBAC authorization mode of k8s
  12. Remember to use it once Asp.Net The development process of core webapi 5.0 + dapper + MySQL + redis + docker
  13. Java Concurrent Programming points
  14. Explain Java I / O flow in detail
  15. Linux system builds springboot project environment and deploys it
  16. Easy to understand JS object-oriented, by the way understand prototype and__ proto__
  17. Summary of java basic knowledge
  18. . net cloud native architect training camp (module 2 basic consolidation rabbitmq mastransit detailed explanation) - learning notes
  19. The architecture of MySQL
  20. MySQL security management, database maintenance and performance improvement
  21. Redis basic command
  22. Summary of MySQL articles
  23. 2、 Create k8s cluster in 5 seconds
  24. data自定义属性在jQuery中的用法
  25. Linux常见解压缩
  26. Detailed explanation of HBase basic principle
  27. 1、 Why and how to learn k8s
  28. Java advanced (29) -- HashMap set
  29. java中大文件上传
  30. Weblogic 2017-3248 analysis of Java Security
  31. Kubernetes official java client 8: fluent style
  32. Explain the function of thread pool and how to use it in Java
  33. Programming software tutorial video Encyclopedia: C + + / Java / Python / assembly / easy language (with tutorial)
  34. Description of dependency problem after javacv is updated to 1.5. X and how to reduce the size of dependency package
  35. Java reflection & dynamic agent
  36. Building Apache 2.4 + php7 + mysql8 in centos7 environment
  37. Summary of Java multithreading (1)
  38. Oracle AWR report generation
  39. Four magic functions of mybatis, don't step on the pit!
  40. A 16-year-old high school student successfully transplanted Linux to iPhone and posted a detailed guide
  41. Centos7 one click installation of JDK1.8 shell script
  42. Mounting of file system in Linux (centos7)
  43. How does serverless deal with the resource supply demand of k8s in the offline scenario
  44. Detailed explanation of HBase basic principle
  45. Spring security oauth2.0 authentication and authorization 4: distributed system authentication and authorization
  46. Redis performance Part 5 redis buffer
  47. JavaScript this keyword
  48. Summary of Java multithreading (3)
  49. Sentry(v20.12.1) K8S 云原生架构探索, SENTRY FOR JAVASCRIPT 手动捕获事件基本用法
  50. Sentry(v20.12.1) K8S 云原生架构探索, SENTRY FOR JAVASCRIPT 手动捕获事件基本用法
  51. (10) Spring from the beginning to the end
  52. Summary of Java multithreading (2)
  53. Spring source notes! From the introduction to the source code, let you really understand the source code
  54. A stormy sunny day
  55. Zookeeper (curator), the implementation of distributed lock
  56. Show the sky! Tencent T4's core Java Dictionary (framework + principle + Notes + map)
  57. Spring boot project, how to gracefully replace the blank value in the interface parameter with null value?
  58. Spring boot project, how to gracefully replace the blank value in the interface parameter with null value?
  59. docker+mysql集群+读写分离+mycat管理+垂直分库+负载均衡
  60. docker+mysql集群+读写分离+mycat管理+垂直分库+负载均衡