1.修改Spring Boot 主类
@SpringBootApplication
@EnableAsync //开启异步任务
public class Application {
@Bean(name="processExecutor")
public TaskExecutor workExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("Async-");
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setMaxPoolSize(20);
threadPoolTaskExecutor.setQueueCapacity(600);
threadPoolTaskExecutor.afterPropertiesSet();
return threadPoolTaskExecutor;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.定义异步类
@Component
public class AsyncTask {
@Async("processExecutor")
public void start() {
double random = Math.random();
int sleepInt = (int) (random * 2000);
try {
Thread.sleep(sleepInt);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3.使用:
在其他类中:
@Component
public class User {
@Autowired
private AsyncTask asyncTask;
asyncTask.start();
asyncTask.start();
asyncTask.start();
@SpringBootApplication
@EnableAsync //开启异步任务
public class Application {
@Bean(name="processExecutor")
public TaskExecutor workExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("Async-");
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setMaxPoolSize(20);
threadPoolTaskExecutor.setQueueCapacity(600);
threadPoolTaskExecutor.afterPropertiesSet();
return threadPoolTaskExecutor;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.定义异步类
@Component
public class AsyncTask {
@Async("processExecutor")
public void start() {
double random = Math.random();
int sleepInt = (int) (random * 2000);
try {
Thread.sleep(sleepInt);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3.使用:
在其他类中:
@Component
public class User {
@Autowired
private AsyncTask asyncTask;
asyncTask.start();
asyncTask.start();
asyncTask.start();
}
注意:ThreadPoolTaskExecutor 的使用非常重要,之前没有配置它导致@Async无效