当前位置:网站首页>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
边栏推荐
- ByteVCharts可视化图表库,你想要的我都有
- Calculate pie chart percentage
- True math problems in 1959 college entrance examination
- Nodejs installation and environment configuration
- Redis "8" implements distributed current limiting and delay queues
- vscode如何比较两个文件的异同
- DDT + Excel for interface test
- An essay on the classical "tear down the wall in thinking"
- Pytorch: the pit between train mode and eval mode
- Pycham connects to the remote server and realizes remote debugging
猜你喜欢
Dlib of face recognition framework
扫码登录的原理你真的了解吗?
Phpstudy V8, a commonly used software for station construction 1 graphic installation tutorial (Windows version) super detailed
org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
Construction of promtail + Loki + grafana log monitoring system
Smart doc + Torna generate interface document
Nifi fast installation and file synchronization
面试百分百问到的进程,你究竟了解多少
阿里研发三面,面试官一套组合拳让我当场懵逼
How to choose the wireless gooseneck anchor microphone and handheld microphone scheme
随机推荐
About background image gradient()!
Query the data from 2013 to 2021, and only query the data from 2020. The solution to this problem is carried out
Introduction to new functions of camtasia2022 software
STM32__03—初识定时器
Detailed explanation of Niuke - Gloves
漫画:什么是IaaS、PaaS、SaaS?
Paging the list collection
Dancenn: overview of byte self-developed 100 billion scale file metadata storage system
Public variables of robotframework
vscode如何比较两个文件的异同
Deepinv20 installation MariaDB
04 Lua 运算符
Nodejs reads the local JSON file through require. Unexpected token / in JSON at position appears
Dlib of face recognition framework
How does flash cache data in memory?
CentOS MySQL multi instance deployment
Kunteng full duplex digital wireless transceiver chip kt1605 / kt1606 / kt1607 / kt1608 is suitable for interphone scheme
信息摘要、数字签名、数字证书、对称加密与非对称加密详解
LVM and disk quota
文件操作详解(2)