当前位置:网站首页>[multithreading] use the thread pool to implement a simple thread pool
[multithreading] use the thread pool to implement a simple thread pool
2022-06-30 19:36:00 【51CTO】
Catalog
- Why introduce thread pool
- Why is the thread pool released faster than the system request ?
- Java The thread pool in the standard library uses
- Thread pools execute processes
- Implement thread pool manually
- Code
Why introduce thread pool
We know that every time we create start-up The cost of destroying a thread is large Therefore, the biggest advantage of introducing thread pool is to reduce the number of threads per startup Destroy thread loss
So how did he achieve the reduction ?
There is a blocking queue in the thread pool He will record and store the tasks to be performed In addition, there will be one or several threads inside the queue to fetch the first element of the random task
Just a quick example :
Namely There is an express station An express The boss of the express station will hire a student to deliver the express Then immediately fire people Another express, he will hire another student And fired At this point he will find It's too much trouble to hire and dismiss like this So he hired a student or a student Then take a notebook to record the future express delivery Let several students take turns to see the express to be delivered in this notebook And then send them to the express This is a thread pool
Why is the thread pool released faster than the system request ?
To understand the problem , We have to understand a set of important concepts .
stay
operating system
in , We are divided into two states :1、 User mode
2、 Kernel mode
In order to deepen “ Kernel mode ” and “ User mode ” The understanding of the .
Take an example of image :
below , Let's take a look Java What is embodied in the standard library .
Old rules , Let's learn Java Make sure you are in the library , The use of thread pools .
Then implement a thread pool by yourself .
Java The thread pool in the standard library uses
ThreadPoolExecutor
Create a thread pool in which parameters are understood
corePoolSize
: Number of core threads
maximumPoolSize
: Maximum number of threads
keepAliveTime
: Amount of free time
unit
: A unit of free time
workQueue
: Blocking / Mission / Work queue
threadFactory
: Thread creation factory
handler
: Refusal strategy
ThreadPoolExecutor
Executors
A simplified version of thread pool is also provided in the standard library ----》
Executors
Executors: The essence is for ThreadPoolExecutor It was packaged , Some default parameters are provided .
Let's take a look now Executors How does it work ? By the way, we simulate a thread pool according to this .
Let's use the first newFixedThreadPool Method . To accomplish a task
Thread pools execute processes
According to the scene above , We can imagine ourselves as the boss of the express station , Just imagine , If someone comes and sends something , Then I'll hire a temporary worker , When it's done , Immediately dismiss him , Yes, yes , But it doesn't seem very cost-effective , After all, the cost of hiring and firing temporary workers frequently begins to be relatively large .
brainwave , I decided to follow the actual needs of my shop , Employ 3 Regular employees , If all three of them are busy , Then I will put the package to be sent in my shop first , When the three of them have finished handling their parcels , Just continue to deal with the parcels piled up in the store , The cost is not very big , The days are light ~
But I didn't think ,618 The activity caught me by surprise , Soon my shop was full of , Three regular employees can't handle it , What if someone still comes to send the package at this time , Don't break the sender's heart ~ To show our strength , Small as the shop is , You can still stand a few more people , Don't panic , I wish I could hire more temporary workers , Site restrictions , My shop can only stand at most 6 personal , That is, I can only hire 3 A temporary worker , It's comfortable now .
But good days don't last long , Or am I too young , Underestimated the strength of consumers , Soon , Parcels piled up in the shop , Watching the six of them busy , I also feel bad , here , And a steady stream of people came to send packages , this time , I really can't help it , The heart that should be hurt still needs to be hurt , The spirit is willing but the flesh is weak , I had to refuse and tell them to find another place ~
After being a boss, you have to take it easy , Compare the flow chart above to understand the process pool ~ The core thread corresponds to 3 A regular employee , The blocking queue corresponds to the parcel storage area of the express store , The thread pool corresponds to the front desk of the store ( At most 6 personal ).
Implement thread pool manually
What's in the thread pool ?
1、 First be able to
Describe task
------> Use it directlyRunnable
that will do2、 need
Organizational tasks
----- > Use it directlyBlockingQueue
Blocking queues3、 Describe worker threads
4、 Organize worker threads
5、 Need to achieve , Add tasks to the thread pool .
The thread pool I want to implement , Not just managing tasks and Threads , They also need to cooperate with each other .
- There is a class that describes what a specific thread does ( With the help of Runnable Realization )
- A blocking team is needed to record several missions BlockingQueue
- Need a class to work on implementing threads
- You need a linked list to store all threads For our convenience shutdown All threads
Code
边栏推荐
- Neon optimization 2: arm optimization high frequency Instruction Summary
- France a+ France VOC label highest environmental protection level
- Year after year, why is breaking the data island still the primary task of enterprise development
- MySQL recursion
- Memory Limit Exceeded
- 【已解决】抖音如何取消关注已注销的账户
- Electron 入门
- Safe holidays without holidays, VR traffic makes children travel safely | Guangzhou Sinovel viewpoint
- Configure server environment
- 笔记软件的历史、选择策略以及深度评测
猜你喜欢
Pyth Solana is a bridge connecting reality on the chain
设计电商秒杀系统
如何使用物联网低代码平台进行服务管理?
Brief introduction of Feature Engineering in machine learning
小小笔记-整型提升(C语言)
项目配置了eslint,编辑器没有关闭eslint功能的情况下,eslint没有生效
4个技巧告诉你,如何使用SMS促进业务销售?
ArcGIS no plug-in load (no offset) day map
笔记软件的历史、选择策略以及深度评测
Browser window switch activation event visibilitychange
随机推荐
20220607 fell below the recommended retail price, and the GPU market is moving towards oversupply
ArcGIS无插件加载(无偏移)天地图
torch. roll
Final chapter of binary tree
Go language learning tutorial (10)
详解kubernetes备份恢复利器 Velero | 深入了解Carina系列第三期
Kalman filter -- Derivation from Gaussian fusion
4个技巧告诉你,如何使用SMS促进业务销售?
Is it safe to open an account for mobile phone stock trading!?
VMware16安装Win11虚拟机(最全步骤+踩坑)
说实话ThreadLocal真不是啥高级的东西
What securities dealers recommend? In addition, is it safe to open a mobile account?
German agbb VOC hazardous substances test
Gateway服务网关
nats集群部署
Develop those things: how to add text watermarks to videos?
Brief introduction of Feature Engineering in machine learning
一文详解|Go 分布式链路追踪实现原理
Huaxing Securities: kitex practice under the original hybrid Cloud Architecture
The folder is transferred between servers. The folder content is empty