SpingBoot异步执行多线程配置方式,有2种方式。

 

方式1.利用java的线程池Executor

第一步:需要在项目中启用异步支持,在启动类加上@EnableAsync注解

第二步:写一个配置类,类上面要加@Configuration注解。配置如下:

  1. @Bean("myAsync")public Executor myAsync() {
  2. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  3. executor.setCorePoolSize(5);
  4. executor.setMaxPoolSize(10);
  5. executor.setQueueCapacity(100);
  6. executor.setThreadNamePrefix("ShopService-");
  7. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  8. executor.initialize();
  9. return executor;
  10. }
 

第三步:是在需要使用异步的方法或者类上面加注解@Async即可

方式2.使用ExecutorService来实现,方法如下:

第一步:写一个配置类,类上面要加@Configuration注解。配置如下:

  1. @Bean
  2. public ThreadPoolExecutorFactoryBean shopPayExecutorFactoryBean() {
  3. ThreadPoolExecutorFactoryBean executorFactoryBean = new    ThreadPoolExecutorFactoryBean();
  4. executorFactoryBean.setCorePoolSize(10);
  5. executorFactoryBean.setMaxPoolSize(100);
  6. executorFactoryBean.setQueueCapacity(300);
  7. executorFactoryBean.setThreadNamePrefix("shop-pay-");
  8. executorFactoryBean.setWaitForTasksToCompleteOnShutdown(true);
  9. executorFactoryBean.setAwaitTerminationSeconds(500);
  10. return executorFactoryBean;
  11. }
  12. @Bean(name = "executorService")
  13. public ExecutorService shopPayExecutor() {
  14. return shopPayExecutorFactoryBean().getObject();
  15. }
 

第二步:在需要使用的类自动注入ExevutorService,然后使用其execute方法来执行。如下:

  1. @Autowired
  2. ExecutorService executorService;@Test
  3. public void executorServiceTest() {
  4. executorService.execute(() -> System.out.println("NOW:" + Thread.currentThread().getName()));
  5. }