当前位置:网站首页>Seven parameters of thread pool and reject policy
Seven parameters of thread pool and reject policy
2022-06-11 14:22:00 【Jinqingze】
Thread pool
summary
Why do you need to use thread pools ?
Review the database connection pool we have known before , When the database connection pool is not used , The connection object needs to be destroyed after each use , The next time you use it, you need to create , It takes time .
After using the database connection pool , Some connection objects will be created in advance , Put it in the pool , Remove from the connection pool when necessary , Put it back in the pool .
The same is true of thread pools , If there are a lot of threads , Frequent thread creation and destruction can take a lot of time . stay jdk5 Before that, the thread pool was implemented manually ,jdk5 after ,java Built in thread pool support .
jdk5 Added ThreadPoolExecutor Implement thread pool , Use at the same time Executors Create different types of thread pools :
newSingleThreadExecutor: Create a single thread pool , Because the abnormal end will create a new .
newFixedThreadPool: Create a fixed-size thread pool . Add threads one by one according to the submitted tasks , The guidance maximum remains unchanged . If it ends because of an exception , A new thread supplement will be created .
newCachedThreadPool: Create a cacheable thread pool . Automatically add or recycle threads according to the task .
But it is not generally provided Executors Class to create .
Advantages of thread pool :
Reuse threads , Reduce the resource consumption caused by thread creation and destruction .
Unified management thread , The creation and destruction of threads are managed by the thread pool .
Improve response time , Thread creation is complete , When the task comes, it can be handled directly , Saves creation time .
ThreadPoolExecutor class
Four construction methods are provided , But the other three constructor methods end up calling 7 The construction of parameters .
7 The meaning of parameters
corePoolSize: Core thread pool size , After creating the object , There are no threads in the pool by default , When a task arrives, a thread will be created to execute , After the execution , The thread will not be destroyed . Know to create an equal number of threads out of the core pool size .
Unless you use prestartAllCoreThreads() perhaps prestartCoreThread() Method , The thread pool will create a thread before the task arrives .
maximumPoolSize: Next time you hang Chi maximum thread out , Indicates how many threads can be created in the thread pool .
keepAliveTime: Indicates how long the thread will be destroyed after no task is executed . By default, only when the number of threads is greater than the core pool , It works , Until the number of threads in the thread pool does not exceed corePoolSize.
unit: Parameters KeepAliveTime Time unit of , Yes 7 The value of , stay TimeUnit There are 7 Static properties in ( God 、 Hours 、 minute 、 second 、 millisecond 、 subtle 、 nanosecond )
workQueue: A blocking queue , Used to store tasks waiting to be executed , The choice of this parameter is very important , Can have a significant impact on how the thread pool is run .
threadFactory: Create factories to create threads .
handler: Indicates the rejection policy of the thread pool , There are four kinds. .
Execution of thread pool
After creating the thread pool , Every time you submit a task , Will use execute Method , The flow chart is as follows :

- If the number of threads in the thread pool is less than the number in the core pool , Threads will be created to execute tasks in the core pool .
- If the number of threads in the thread pool is greater than the number in the core pool , Will determine whether the queue is full , If not, add the task to the queue .
- If the number of threads in the queue is full , Determine whether the number of threads is greater than the maximum number of threads , If less than the maximum quantity , Will create non core threads to perform tasks .
- If the number of threads is greater than the maximum number , Can execute execution strategy .
Queue in thread pool
SynchronousQueue: Synchronous queue type one capacity only 1 Queues , The submitted task will not be saved , Just create a new thread to execute the new task .
ArrayBlockingQueue: Bounded queues , Is a bounded blocking queue implemented with arrays , Press FIFO Sorting quantity .
LinkedBlockingQueue: Capacity queue can be set , Blocking queue based on linked list , Press FIFO Sorting task , Capacity can be set , If it is not set, it is a borderless blocking queue , Maximum length is Integer.MAX_VALUE.
Rejection policy for thread pool
Thread pools provide four types of denial policies
- AbortPolicy Strategy , Will throw an exception directly
- CallerRunsPolicy Strategy , As long as the thread pool is not closed , This policy runs the current task in the calling thread ( If the mission is rejected , The thread submitting the task ( for example main) Perform this task directly )
- DiscardOledestPolicy Strategy , Discard the oldest request , Try to commit the current task again .
- DiscardPolicy Strategy , Discard unmanageable tasks , Nothing to do with .
/* Mission */
public class MyTask implements Runnable {
private int taskNum;
public MyTask(int num) {
this.taskNum = num;
}
@Override
public void run() {
try {
Thread.currentThread().sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":task "+taskNum+" completion of enforcement ");
}
}
/* Modify the rejection policy in the test class to see the characteristics and differences */
public class Test {
public static void main(String[] args) {
// Creating a thread pool 7
ThreadPoolExecutor executor = new ThreadPoolExecutor(2,
5, 200,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(2),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
for(int i=1;i<=20;i++){
MyTask myTask = new MyTask(i);
executor.execute(myTask);// Add tasks to thread pool
//Future<?> submit = executor.submit(myTask);
}
executor.shutdown();
}
}
execute And submit The difference between
Perform tasks in addition to using execute The method can also be used submit Method .
execute Suitable for situations where the return value is not a concern
submit The method is suitable for situations where you need to focus on the return value
Close thread pool
Close thread pool to call shutdownNow and shutdown Two ways to achieve .
shutdownNow: Issue to the executing thread interrupt(), Stop executing , All tasks that have not been started will be cancelled , Return to the list of tasks that have not yet started .
shutdown: The thread pool no longer accepts new tasks , A single page does not force the termination of tasks that have been submitted or are being executed .
边栏推荐
- 高通WLAN框架学习(29)-- 6GHz 概述
- Powerful full text search tool anytxt searcher
- mysql创建表出错1067 - Invalid default value for ‘update_time‘
- Lake Shore HR series sensors
- 【公开课预告】:MXPlayer OTT音视频转码实践和优化
- Pond (topology + priority queue)
- Task manager based on Qt development
- Why does each running Department display that the database already exists, delete the database, and then succeed? Each running department must delete the database, and re run the whole successfully
- 线程池的七个参数与拒绝策略
- C # set the cursor shape of forms and systems
猜你喜欢

AGV robot RFID sensor ck-g06a and Siemens 1200plc Application Manual

阿里一面,谈谈策略模式在项目中的使用

【公开课预告】:MXPlayer OTT音视频转码实践和优化

Telecommuting with cpolar (1)

Leetcode 1962. 移除石子使总数最小(应该是向上取整)

Just after the college entrance examination, I was confused and didn't know what to do? Tell me what I think

三级分类展示

Container -- reverse content -- use of explosion, splicing, and inversion functions

mysql创建表出错1067 - Invalid default value for ‘update_time‘

.NET C#基础(6):命名空间 - 有名字的作用域
随机推荐
Part 23, two-way circular linked list model.
Alibaba Cloud 3 (Soaring Falcon) x86_ 64 (py3.7.8) system Yum source
MySQL advanced statement
C # set the cursor shape of forms and systems
2022 Gansu Province safety officer B certificate test question simulation test question bank and online simulation test
MySQL数据库创建索引的方法和好处
漫画:有趣的 “切蛋糕“ 问题
Private collection project practice sharing [Yugong series] February 2022 wechat applet -app Other properties of JSON configuration properties
Is the brokerage account given by qiniu business school safe? Do you charge for opening an account
提取式存储才是最佳的记忆方法
Current situation and future development trend of metal organic chemical vapor deposition (MOCVD) market in the world and China from 2022 to 2028
Easyexcel configuration and Application
gensim.models word2vec 参数
mysql创建表出错1067 - Invalid default value for ‘update_time‘
2022-2028 global and Chinese near field scanning optical microscope (NSOM) market status and future development trend
Check box select all or deselect all
Methods and benefits of creating indexes for MySQL databases
【Try to Hack】URL
How to quickly compress the size of video?
使用cpolar远程办公(1)