当前位置:网站首页>Talking about thread pool with pictures and texts
Talking about thread pool with pictures and texts
2022-06-10 05:28:00 【Bug trendsetter】
Basic composition
1、 Thread pool manager (ThreadPool): Used to create and manage thread pools , Include Creating a thread pool , Destroy thread pool , Add a new task ;
2、 The worker thread (PoolWorker): Threads in thread pool , Waiting when there is no task , You can cycle through tasks ;
3、 Task interface (Task): The interface that each task must implement , For worker threads to schedule the execution of tasks , It mainly specifies the entry of tasks , The end of the task , Task execution status, etc ;
4、 Task queue (taskQueue): Used to store unprocessed tasks . Provide a buffer mechanism .
Reduce resource consumption . Reduces the cost of thread creation and destruction by reusing created threads .
Improve response time . When the mission arrives , Tasks can be executed without waiting for thread creation .
Improve the manageability of threads . Uniform allocation is possible using thread pools , Tune and monitor , Delayed execution 、 Strategy of timing cycle execution, etc .

java.uitl.concurrent.ThreadPoolExecutor Class is the most core class in the thread pool
Construction parameters
java.uitl.concurrent.ThreadPoolExecutor Class is the most core class in the thread pool
Construction parameters
public ThreadPoolExecutor(
int corePoolSize, // The maximum number of core threads in the thread pool . When a thread pool creates a new thread , If the current total number of threads is less than corePoolSize, The core thread is created , If exceeded corePoolSize, The new thread is a non core thread By default, core threads live in the thread pool all the time , Even if this core thread does nothing ( Idle state ). If specified ThreadPoolExecutor Of allowCoreThreadTimeOut This property is true, So if the core thread doesn't work ( Idle state ) Words , Over a certain period of time ( The duration is determined by the following parameters ), Will be destroyed
int maximumPoolSize,//( The maximum number of threads that can be created when there are not enough threads ) Total threads = Number of core threads + Number of non core threads
long keepAliveTime, // Idle timeout of non core thread
TimeUnit unit, // keepAliveTime The unit of ,TimeUnit Is an enumerated type
BlockingQueue<Runnable> workQueue, // Task queue : Maintaining the Runnable object When all the core threads are working , The newly added task will be added to the queue to wait for processing , If the queue is full , Then create a new non core thread to execute the task
ThreadFactory threadFactory, // Create a new thread ,Executors.defaultThreadFactory()
RejectedExecutionHandler handler) // Thread pool saturation strategy 
adopt ThreadPoolExecutor.execute(Runnable command) Method to add a task to the thread pool
When a task is added to the thread pool :

1、 Number of threads not reached corePoolSize, Create a new thread ( Core thread ) Perform tasks
2、 The number of threads has reached corePools, Then move the task to the queue BlockingQueue wait for
3、 If you can't add tasks to BlockingQueue( The queue is full ), Then in non corePool Create a new thread to handle the task ( Be careful , To perform this step, you need to obtain a global lock ).
4、 The queue is full , The number of bus routes has reached maximumPoolSize,(RejectedExecutionHandler) Throw an exception


Four kinds of java Implement a good thread pool
CachedThreadPool()
Cacheable thread pool :
There is no limit to the number of threads
If there are idle threads, they will be reused , Create a new thread if there are no idle threads
Make sure programs are created less frequently / Destruction of the thread , Reduce system overhead
FixedThreadPool()
Fixed-length thread pool :
You can control the maximum number of concurrent threads ( Number of threads executing at the same time )
The exceeded thread will wait in the queue
ScheduledThreadPool()
Fixed-length thread pool :
Support regular and periodic task execution .
SingleThreadExecutor()
Singleton thread pool :
There is only one worker thread to perform the task
All tasks are executed in the specified order , That is to follow the rules of the queue
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);
}
}
The state of the thread pool




Thread pool risk :
Deadlock 、 Insufficient resources 、 Concurrency error 、 Thread leak 、 Request overload
perform execute() Methods and submit() What's the difference between methods ?
execute() Method is used to submit tasks that do not require a return value , Therefore, it is impossible to judge whether the task is successfully executed by the thread pool ;
submit() Method is used to submit tasks that require a return value . The thread pool will return a future Object of type , Through this future Object can determine whether the task is executed successfully , And through future Of get() Method to get the return value ,get() Method blocks the current thread until the task is completed , While using
get(long timeout,TimeUnit unit)Method will block the current thread for a period of time and return to , At this time, it is possible that the task is not finished .
source: //490.github.io/Java Multithreading and concurrency /Remember to point 「 Fabulous 」 and 「 Looking at 」↓
Love you
边栏推荐
- Personnaliser le plug - in bulles JS prompt tooltips
- openGauss数据库性能调优概述及实例分析
- Hevc HM learning 01
- Safari's favorites item does not appear on the home page
- Bubble Sort Bubble_ sort
- Flutter DIO example
- Interview question 05.04 Next number
- MTK 平台sensor arch 介绍-kernel
- 2022.5.31-----leetcode. Sword finger offer one hundred and fourteen
- Talk about the importance of technology and tasks
猜你喜欢

photoClip.js手机图片上传截取插件

五项最优!蚂蚁集团通过信通院“稳保计划”最高级评测

Initial experience of using XXL job

【UE4自动地形材质】

Hevc HM learning 01

Read leastereo:hierarchical neural architecture search for deep stereo matching

Literature reading -- location of regulatory variation in maize drought response and tolerance gene expression

【对话直播】图计算是下一个科技前沿

With the advent of the digital wave, how to achieve agile business delivery and sustainable technology governance? Uncover the ant bizstack

photoClip. JS mobile image upload and interception plug-in
随机推荐
Talk about "honest responsibility" in ant AI technology
Overview and example analysis of opengauss database performance tuning
.NET C#基础(7):接口 - 人如何和猫互动
蚂蚁集团隐私计算一体机获得双认证,83项指标均达要求
MySQL advanced CRUD
一文看懂蚂蚁BizStack 云原生开发和治理平台
[how much management knows] Chinese "other", English "other", Japanese "other"
The meaning of likelihood function
Pytorch: sub model parameter freezing + BN freezing
R language performs double sample t-test on multiple covariates based on lapply function, Welch double sample t-test analysis and double independent sample t-test on the mean of covariates correspondi
Interview question 08.08 Permutation with duplicate strings
Curator - Create Client
[nick] intensive reading
Display常用英文缩写
The R language catools package divides the data, randomforest package constructs the random forest model, uses the predict function to carry out model prediction and reasoning on the test data set, an
Power mathematics of leetcode326-3
[STM32] transplantation of Hal library on 4-pin 0.96 inch OLED screen - hardware IIC (I)
【UE4自动地形材质】
photoClip. JS mobile image upload and interception plug-in
Personnaliser le plug - in bulles JS prompt tooltips