当前位置:网站首页>Multithreaded @ async thread pool
Multithreaded @ async thread pool
2022-04-23 16:50:00 【Kramer_ one hundred and forty-nine】
ThreadPoolExecutor
ThreadPoolExecutor yes JDK Native thread pool
Reference article
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
// Omit the relevant code
}
- corePoolSize
Number of core threads - maximumPoolSize
Maximum number of threads - keepAliveTime
The maximum number of threads that can survive , Is the maximum time that can be reserved in the thread pool except for the core thread , Because in the process pool , Except for the core thread, it cannot be cleared even when there is no task , The rest have survival time , It means the longest idle time that a non core thread can keep - unit
Calculation keepAliveTime The unit of - workQueue
Blocking ( wait for ) queue . Altogether ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue etc. 7 Blocking queue - threadFactory
A factory for creating threads , Mainly used to create threads , The default is normal priority 、 Non-daemon thread . - handler
Refusal strategy . There are four kinds : -
- AbortPolicy
Do not perform new tasks , Throw an exception directly , Indicates that the thread pool is full
- AbortPolicy
-
- DisCardPolicy
Do not perform new tasks , Don't throw an exception
- DisCardPolicy
-
- DisCardOldSetPolicy
Replace the first task in the message queue with the current new task execution
- DisCardOldSetPolicy
-
- CallerRunsPolicy
Call directly execute To perform the current task
- CallerRunsPolicy
Example :
public class ThreadPoolTest {
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(3,5,1L, TimeUnit.SECONDS,new ArrayBlockingQueue(4),Executors.defaultThreadFactory());
for(int i=0;i<7;i++){
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+" "+"---> Handle the business ");
});
}
executorService.shutdown();
}
}
Spring ThreadPoolTaskExecutor
Example
Add on asynchronous method @Async annotation , And then you need to @SpringBootApplication Start class or @Configuration Annotation class adding annotations @EnableAsync Start multithreading annotation ,@Async Asynchronous multithreading will be started for the marked method , Be careful , The class of this method must be handed over to Spring Container to manage
The configuration file application.properties
# Number of core thread pools
spring.task.execution.pool.core-size=5
# Maximum number of thread pools
spring.task.execution.pool.max-size=10
# The capacity of the task queue
spring.task.execution.pool.queue-capacity=5
# Lifetime of non core threads
spring.task.execution.pool.keep-alive=60
# Prefix name of thread pool
spring.task.execution.thread-name-prefix=god-jiang-task-
Configuration class AsyncScheduledTaskConfig.java
@Configuration
public class AsyncScheduledTaskConfig {
@Value("${spring.task.execution.pool.core-size}")
private int corePoolSize;
@Value("${spring.task.execution.pool.max-size}")
private int maxPoolSize;
@Value("${spring.task.execution.pool.queue-capacity}")
private int queueCapacity;
@Value("${spring.task.execution.thread-name-prefix}")
private String namePrefix;
@Value("${spring.task.execution.pool.keep-alive}")
private int keepAliveSeconds;
@Bean
public Executor myAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// Maximum number of threads
executor.setMaxPoolSize(maxPoolSize);
// Number of core threads
executor.setCorePoolSize(corePoolSize);
// The size of the task queue
executor.setQueueCapacity(queueCapacity);
// Thread prefix name
executor.setThreadNamePrefix(namePrefix);
// Thread lifetime
executor.setKeepAliveSeconds(keepAliveSeconds);
/** * Refuse to deal with the strategy * CallerRunsPolicy(): Let the caller thread run , such as main Threads . * AbortPolicy(): Throw an exception directly . * DiscardPolicy(): Direct discarding . * DiscardOldestPolicy(): Discard the oldest task in the queue . */
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// Thread initialization
executor.initialize();
return executor;
}
}
Service
@Component
@EnableAsync
public class ScheduleTask {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Async("myAsync")
@Scheduled(fixedRate = 2000)
public void testScheduleTask() {
try {
Thread.sleep(6000);
System.out.println("Spring1 Native thread pool " + Thread.currentThread().getName() + "-" + sdf.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Async("myAsync")
@Scheduled(cron = "*/2 * * * * ?")
public void testAsyn() {
try {
Thread.sleep(1000);
System.out.println("Spring2 Native thread pool " + Thread.currentThread().getName() + "-" + sdf.format(new Date()));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
版权声明
本文为[Kramer_ one hundred and forty-nine]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231359460728.html
边栏推荐
- Public variables of robotframework
- DDT + Excel for interface test
- Esxi encapsulated network card driver
- True math problems in 1959 college entrance examination
- Detailed explanation of the penetration of network security in the shooting range
- New project of OMNeT learning
- JMeter installation tutorial and solutions to the problems I encountered
- Set cell filling and ranking method according to the size of the value in the soft report
- Change the password after installing MySQL in Linux
- Do you really understand the principle of code scanning login?
猜你喜欢
Installing labellmg tutorial in Windows
CentOS MySQL multi instance deployment
Selenium IDE and XPath installation of chrome plug-in
Rtklib 2.4.3 source code Notes
TypeError: set_figure_params() got an unexpected keyword argument ‘figsize‘
OMNeT学习之新建工程
Bytevcharts visual chart library, I have everything you want
DanceNN:字节自研千亿级规模文件元数据存储系统概述
Dlib of face recognition framework
Nodejs reads the local JSON file through require. Unexpected token / in JSON at position appears
随机推荐
Nodejs reads the local JSON file through require. Unexpected token / in JSON at position appears
Zhongang Mining: Fluorite Flotation Process
5-minute NLP: text to text transfer transformer (T5) unified text to text task model
Loggie source code analysis source file module backbone analysis
【Pygame小游戏】10年前风靡全球的手游《愤怒的小鸟》,是如何霸榜的?经典回归......
Regular filtering of Intranet addresses and segments
LVM and disk quota
众昂矿业:萤石浮选工艺
网络安全之渗透靶场实战详解
关于局域网如何组建介绍
◰ GL shader handler encapsulation
织梦DEDECMS安全设置指南
Server log analysis tool (identify, extract, merge, and count exception information)
04 Lua operator
Selenium IDE and XPath installation of chrome plug-in
org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
File upload and download of robot framework
Detailed explanation of information abstract, digital signature, digital certificate, symmetric encryption and asymmetric encryption
Project framework of robot framework
Detailed explanation of UWA pipeline function | visual configuration automatic test