当前位置:网站首页>[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 systemin , We are divided into two states :1、 User mode2、 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 directlyRunnablethat will do2、 need
Organizational tasks----- > Use it directlyBlockingQueueBlocking 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

边栏推荐
- German agbb VOC hazardous substances test
- Entropy - conditional entropy - joint entropy - mutual information - cross entropy
- Makefile笔记(一文学会Makefile)
- 微信小程序快速入门 --项目介绍
- Develop those things: how to add text watermarks to videos?
- Practical application of "experience" crawler in work
- com. alibaba. fastjson. Jsonobject tojsonstring eliminate circular reference
- 详解kubernetes备份恢复利器 Velero | 深入了解Carina系列第三期
- Mipi protocol in RFFE
- Connect to lab server
猜你喜欢

Construction and practice of full stack code test coverage and use case discovery system

Swin-Transformer(2021-08)

Video content production and consumption innovation

成长一夏 挑战赛来袭 专属社区福利来袭~免费获得CSDN定制T恤衫

为什么越来越多的人选择云渲染?

Nodejs 安装与介绍

【多线程】使用线程池、实现一个简单线程池

France a+ France VOC label highest environmental protection level

Gateway服务网关

程序员女友给我做了一个疲劳驾驶检测
随机推荐
微信小程序快速入门 --项目介绍
com. alibaba. fastjson. Jsonobject tojsonstring eliminate circular reference
Task04: set operation - addition and subtraction of tables, join, etc. - learning notes of Tianchi Longzhu project SQL training camp
Evolution of screen display technology
10 statistical methods commonly used for "dry goods" data analysis, with key application scenarios attached
企业中通过组策略管理Edge浏览器设置(IE模式、主页绑定等)
Swin-transformer --relative positional Bias
Evolution of screen display technology
mysql中union和union all的区别
Video content production and consumption innovation
BeanUtils.copyProperties() 对比 mapstruct
How to use xUnit framework to maintain test cases?
美国服务器租用和托管服务哪个好?
A common mistake in enterprise model selection
[JetsonNano] [教程] [入门系列] [一] 如何开启VNC共享
Some interesting modules
Ansi/ul 94 class 5-V vertical combustion test
德国AgBB VoC有害物质测试
Ditto设置全局仅粘贴文本快捷键
Influence and requirements of different manufacturing processes on the pad on PCB