当前位置:网站首页>Advanced multithreading (8) -- thread pool
Advanced multithreading (8) -- thread pool
2022-04-22 22:46:00 【Classmate Xiaoqu】
Basic concepts of multithreading : Getting started with multithreading ( One )
Multi thread basic implementation : Getting started with multithreading ( Two )
Multithreading Management : Multithreading Foundation ( 3、 ... and )
State transitions between threads : Multithreading Foundation ( Four )
Communication between threads : Multi thread advanced ( 5、 ... and )
Locking mechanism : Multi thread advanced ( 6、 ... and )
Pessimistic lock and optimistic lock 、CAS: Multi thread advanced ( 7、 ... and )
At present, we talk about multithreading from establishment to use, and then to performance , Creating multiple threads consumes CPU resources , If the thread runs out, destroy , Isn't it a waste of system resources ? How can we reasonably create and use ? Next, let's introduce a common tool ---- Thread pool .
Multi thread advanced ( 8、 ... and )---- Thread pool
1、 Thread pool
1.1 Why use thread pools
- establish / Consuming threads wastes system resources , Using the thread pool, you can reuse the created threads .
- Control the amount of concurrency ( Main cause ), Prevent server crash .
- You can manage threads in a unified way .
1.2 principle
Executor It is the top-level interface of thread pool , Its implementation class is ThreadPoolExecutor, Let's take a look at its implementation :
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- int corePoolSize: The thread pool has a core ⼼ The number of threads is the highest ⼤ value
- int maximumPoolSize: The total number of threads in this thread pool is the highest ⼤ value
- long keepAliveTime:⾮ nucleus ⼼ Thread idle timeout ⻓.
- TimeUnit unit:keepAliveTime The unit of .
- BlockingQueue workQueue: Blocking queues , Maintain the waiting hold ⾏ Of Runnable Mission object .
- ThreadFactory threadFactory: A factory for creating threads
- RejectedExecutionHandler handler: Refuse to deal with the strategy
1.3 ThreadPoolExecutor
Thread pools are the same as threads , It also has its own state and life cycle ;ThreadPoolExecutor Class ⼀ individual volatile int change
The amount runState To represent the state of the thread pool , Respectively RUNNING、SHURDOWN、STOP 、TIDYING 、TERMINATED.

1.4 Multithreaded implementation process
- When the total number of threads <
corePoolSize, Whether the thread is idle or not , Will create a new core thread to execute the task ( In order to quickly reach the maximum number of core threads ); - When the total number of threads >=
corePoolSize, The new task will be put in the waiting queue , If there are idle core threads , Will take tasks from the queue to execute ;( Embodies the Thread reuse ) - If the cache queue is full , And the number of bus passes <
maximumPoolSize, You need to create a non core thread to execute ; - If the cache queue is full , Bus number >=
maximumPoolSize, Then the rejection strategy will be implemented .
1.5 Four common thread pools
1.5.1 newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
When you need to hold ⾏ Many short-term tasks ,CacheThreadPool The thread is complex ⽤ rate ⽐ a ⾼, Will significantly mention ⾼ performance .⽽ And thread 60s It will be recycled later , It means that even if no task comes in , CacheThreadPool It won't account for ⽤ A lot of resources .
1.5.2 newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
As can be seen from the implementation code ,CachedThreadPool Only the number of non core threads can be created ,FixedThreadPool Only the number of core threads can be created .
1.5.3 newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));
}
Yes and no ⼀ A nuclear ⼼ Threads ( corePoolSize == maximumPoolSize=1), send ⽤ 了 LinkedBlockingQueue( The capacity is very ⼤), therefore , Does not create ⾮ nucleus ⼼ Threads . All tasks according to First come, first served ⾏ The order of execution ⾏. If this only ⼀ Your thread is not idle , Then the new task will be stored in the task queue ⾥ Waiting for execution ⾏.
1.5.4 newScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize
return new ScheduledThreadPoolExecutor(corePoolSize);
}
//ScheduledThreadPoolExecutor():
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS, new DelayedWorkQueue());
}
establish ⼀ It 's a decision ⻓ Thread pool ,⽀ Regular and periodic task execution ⾏.
版权声明
本文为[Classmate Xiaoqu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204222207175289.html
边栏推荐
- ACL2022 | 利用中文语言层级异质图强化预训练语言模型
- A journey to C by Xiao Sai Mao -- first understanding of C language (3)
- Centos7安装mysql
- 0-1背包问题讲解 & leetcode相关题目总结
- Catering industry cashier system source code, C # Net + MSSQL WPF
- GBase 8s V8. 8 SQL Guide: Tutorial - 6.2.1 (3)
- 来个 vue 大佬,看看有没有 iframe 缓存方案?
- Infix to suffix expression (inverse Polish) to prefix expression (polish)
- 行人重识别综述之Person Re-identification:Past, Present and Future
- 学习笔记2-0417
猜你喜欢
随机推荐
0基础UnityURP渲染管线之阴影ShadowCaster-ShadowMask-Map傻傻分不清楚(代码向)
PHP wechat refund certificate
R语言数据分析从入门到高级:(九)数据清洗技巧之数据表连接大全
MySql--数据库基础
2.57-编写程序show_short, show_long和show_double,它们分别打印类型为short, long和double的C语言对象的字节表示。请试着在几种机器上运行。
小赛毛游C记——初识C语言(3)
[intranet penetration] - vulnstack (I)
【4.1】flink窗口算子的trigger触发器和Evictor清理器
High end beer is losing young people
2.58-编写程序is-little-endian,当在小端法机器上编译和运行时返回1,在大端法机器上编译和运行时则返回0。这个程序应该可以运行在任何机器上,无论机器的字长是多少。
Reinforcement learning (practice): feedback, AC
Appinventor development
餐饮行业收银系统源码,C# .NET + MSSQL WPF
Graph and numerical representation of knowledge map of knowledge representation
用forEach和ES6实现tab切换
Flutter混合开发
[MRCTF2020]Ez_bypass
51 MCU proteus simulation key control nixie tube digital display
0-1背包问题讲解 & leetcode相关题目总结
Flex layout


![[wechat applet development (cloud wallpaper applet tutorial)]](/img/71/d1ec9b0e7af47427c1e19b9b949bfa.png)





![[summary of scattered knowledge points 5]](/img/a6/6700f00b01bc59fc0366d64071ac41.png)