当前位置:网站首页>Tell your girlfriend easily: the internal principle of thread pool
Tell your girlfriend easily: the internal principle of thread pool
2022-04-22 12:21:00 【Wanmao Society】
A restaurant appointment
The dinner plate is especially crystal white under the light , My girlfriend took a sip of red wine , Said to me, :“ I often hear you say thread pool , What is the principle of thread pool ?” I was in a daze , Think about what happened to my girlfriend today , Why do you suddenly ask such a professional question , But as a professional, I can't be shy in front of my girlfriend , Think about it and say :“ Let me tell you the story of my former colleague Lao Wang !”
Old programmer Wang
Lao Wang is a programmer who has drifted North for more than ten years , Old age , I can't afford to work overtime , There is no hope of promotion , So I took some savings in my hand , Go back home and start a business . He chose the bath industry , Open a bath center , Yes , A formal bath center . When I was in Beijing , The bathhouse I like to go to is called “ Tsinghua pool ”, He thought about it. , Call your bath center “ Thread pool ”.
Thread pool bath center
After the thread pool is opened , Lao Wang found that some customers wanted to do foot therapy , So I recruited 1 A pedicure technician , An extra business added to the revenue . With the increase of foot therapy customers , In order to make more money, I hired again 4 A pedicure technician . After a while , The business of the bath center is getting better and better , More and more people are doing foot therapy . however , Lao Wang found that the foot therapists in his shop already had 5 A pedicure technician , There's too much to recruit , I can't afford to pay any more . What can a foot technician do if he is too busy ? Lao Wang is a wise man , Think of a way : Line up customers , Which pedicure technician has finished , Free time comes out , Just ask another customer in the team to continue .
A busy weekend
One to the weekend , There are several times more customers coming to the bath center than usual , Customers who want pedicure have to wait too long , The customers are impatient . Lao Wang immediately responded , Another urgent recruitment from other bath centers 5 A pedicure technician , Do foot therapy for customers in the team , Greatly reduce the number of customers waiting in line . however , Sometimes business is so hot , Urgent technicians are also using , Customers also have a long queue , And new customers , Lao Wang can only say to customers with a smile on his face :“ Come back next time , Find a good technician for you next time .”, Shut the customer out . After the weekend , We can't keep idle people in the shop , Lao Wang dismissed all the technicians who had been recruited urgently .
Lao Wang's way of Management
Lao Wang's business is booming , We will open a branch soon 、 Financing listing 、 Reach the peak of life . Since it's so successful , Let's review his management :
If you know Lao Wang's business philosophy , The thread pool is easy to understand , hold customer Replace with Mission , hold Pedicure Technician Replace with Threads , Thread pool bath center Namely Thread pool 了 , This is the internal principle of thread pool :
Wake up in a dream
Bell , The alarm woke me up , It turned out to be a dream , I don't have any girlfriend ? There is an interview this morning , Get up and wash , Just set out . Think about that strange dream on the way , Don't review the internal principle of a downline Chengchi any more ! Have a look first ThreadPoolExecutor Class execute Method :
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
// obtain clt,clt It records the status of thread pool and the number of running threads .
int c = ctl.get();
// When the number of running threads is less than the number of core threads , Create threads and put them in the thread pool , And run the current task .
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
// Failed to create thread , Recapture clt.
c = ctl.get();
}
// When the thread pool is running and the number of running threads is greater than the number of core threads , Put the task in the queue .
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
// Recheck that the thread pool is not running ,
// Remove the task from the queue , And through the rejection strategy to deal with the task .
if (! isRunning(recheck) && remove(command))
reject(command);
// The current number of running threads is 0 when , Create threads to join the thread pool .
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// When the number of running threads is greater than the number of core threads and the queue is full ,
// Create threads and put them in the thread pool , And run the current task .
else if (!addWorker(command, false))
// When the number of running threads is greater than the maximum number of threads , If it fails, it refuses the task
reject(command);
}
stay execute In the method , Called many times addWorker Method , Take another look at this method :
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
// obtain clt,clt It records the status of thread pool and the number of running threads .
int c = ctl.get();
// Get the running state of thread pool .
int rs = runStateOf(c);
// Thread pool is closed , Or the current task is null
// Or the queue is not empty , Then directly return to failure .
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
// Get the number of threads in the thread pool
int wc = workerCountOf(c);
// The number of threads exceeds CAPACITY, Then return to false;
// there core yes addWorker The second argument to the method ,
// If true Then compare according to the number of core threads ,
// If false Then compare according to the maximum number of threads .
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
// Try to increase the number of threads , If it works , I jump out of the first one for loop
if (compareAndIncrementWorkerCount(c))
break retry;
// If it fails to increase the number of threads , Then we can get back ctl
c = ctl.get();
// If the current running state is not equal to rs, Indicates that the state has been changed ,
// Return to the first for Loop continuation
if (runStateOf(c) != rs)
continue retry;
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
// Create based on current task Worker object
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// After getting the lock , Recheck thread pool status
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive())
throw new IllegalThreadStateException();
// Add the newly created thread to the thread pool
workers.add(w);
int s = workers.size();
// Record the maximum number of threads in the thread pool
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
// Start thread , Start running tasks
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
interview
A middle-aged man sat in front of me , Said to me, :“ Hello! , I'm the interviewer today .” I replied with a smile :“ Hello! .” The interviewer asked me without expression :“ Thread pool must have been used , Can you talk about the internal principle of thread pool ?” I almost laughed , Say... Confidently ……
版权声明
本文为[Wanmao Society]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221200491336.html
边栏推荐
- JS [detailed] scope
- Pytorch processes RNN input variable length sequence padding
- [concurrent programming 052] talk about double check lock and its advantages?
- How to write a valuable competitive product analysis report?
- ONT和ONU
- LeetCode 1678、设计 Goal 解析器
- "Stack overflow Chinese content" is finally here! Invite you to experience feedback and get a good gift
- Difference between redis setex and set
- [in depth understanding of tcallusdb technology] description of data interface of designated location in replacement list - [list table]
- Efr32 crystal calibration guide
猜你喜欢

Where have all the Internet people who left their jobs gone?
![JS [detailed explanation] closure](/img/3d/1db37e18300c56848ef00928392d0a.png)
JS [detailed explanation] closure

"Open source summer" activity is hot. In the registration, rich bonuses are waiting for you to get!
![【深入理解TcaplusDB技术】读取列表指定位置数据接口说明——[List表]](/img/ed/cccd5dee09d2f0a3e6c788bd265b36.png)
【深入理解TcaplusDB技术】读取列表指定位置数据接口说明——[List表]

Electrician Lecture 2

Developer friendly public chain Neo | how to connect web2 developers to Web3 world

【深入理解TcaplusDB技术】示例代码——异步调用接口
![After brushing a thousand multiple-choice questions, I summarized these error prone points of C language [the second bullet]](/img/3e/12697e1cef1de1698928911e82a98f.png)
After brushing a thousand multiple-choice questions, I summarized these error prone points of C language [the second bullet]
![【深入理解TcaplusDB技术】批量删除列表指定位置数据接口说明——[List表]](/img/ed/cccd5dee09d2f0a3e6c788bd265b36.png)
【深入理解TcaplusDB技术】批量删除列表指定位置数据接口说明——[List表]

Ner brief overview
随机推荐
LeetCode 1678、设计 Goal 解析器
LeetCode 34、在排序数组中查找元素的第一个和最后一个位置
[deeply understand tcallusdb technology] insert data into the specified location of the list interface description - [list table]
What role does RF chip play in mobile phone?
Canvas series tutorial 01 - line, triangle, polygon, rectangle, palette
基于J2EE的房屋租赁系统的设计与实现.rar(论文+项目源码+数据库文件)
Base64 encryption, decryption and JSON processing
Father of MySQL: the code should be written at once, not later
EFR32晶体校准指南
通俗易懂地给女朋友讲:线程池的内部原理
[in depth understanding of tcallusdb technology] scan data interface description - [list table]
[logical fallacies in life] controlling violence with violence and suppressing rationality
NFT, gamefi, socialfi, cloud storage, dfinity, the hottest track in ecology
[concurrent programming 051] implementation principle of volatile memory semantics
电工第二讲
[deeply understand tcallusdb technology] delete all data interface descriptions in the list - [list table]
L3-010 是否完全二叉搜索树 (30 分)
How to write a valuable competitive product analysis report?
. net treasure API: outputformatter, format output object
Set the sliding wheel in vscode to change the font size