There are three steps
- initiator plus@EnableAsync explanatory note
- Add to the methodology@Async explanatory note
- Creating a Thread Pool Configuration Class
1. Startup class plus@EnableAsync explanatory note
@SpringBootApplication
@EnableAsync
public class FacadeH5Application {
public static void main(String[] args) {
(, args);
}
}
2. Add to the methodology@Async explanatory note
@Async
public void m1() {
//do something
}
NOTE: The cause of the@Async Several reasons why annotations fail
- Both methods are inside the same class, and one method calling the other asynchronous method doesn't work. But if you inject your own instance in this class, and then call the asynchronous method through your own instance it works.
- The class where the @Async method resides is not handed over to the spring proxy (without annotations such as @Component), and does not take effect.
- Annotated methods that are not public methods do not take effect.
3. Create a thread pool configuration class
The default thread pool configuration is as follows
# of core threads
-size=8
# Maximum number of threads
-size=16
# Idle threads alive
-alive=60s
# Allow core thread timeout
-core-thread-timeout=true
# Number of thread queues
-capacity=100
# Number of thread queues -capacity=100
-termination=false
-termination-period=
# Thread name prefix
-name-prefix=task-
Creating a Thread Pool Configuration Class
@Configuration
public class ThreadPoolConfig {
@Bean
public TaskExecutor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// Set the number of core threads
(10);
//Set the maximum number of threads
(20); //Set the maximum number of threads.
//Set the queue capacity
(20).
//Set thread active time
(30); //Set thread name prefix.
//Set thread name prefix
("sendSms-");
//Set the denial policy
(new ()); //Wait for all tasks to finish before closing the thread.
//Wait for all tasks to finish before closing the thread pool
(true);
//Set the waiting time for tasks in the thread pool
(60);
return executor.
}
}
Configuring multiple thread pools
Sometimes, if you have more than one thread pool configured in a project, you need to add the name of the thread pool after the @Bean
@Configuration
public class ThreadPoolConfig {
@Bean("ThreadPool1")
public TaskExecutor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
......
return executor;
}
@Bean("ThreadPool2")
public TaskExecutor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
......
return executor;
}
}
When using the @Async annotation you need to specify the specific thread pool to use, in the following format
@Async("ThreadPool1")
public void m1() {
//do something
}