ThreadPoolTaskConfig.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package ieven.server.webapp.infrastructure;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  5. import java.util.concurrent.ThreadPoolExecutor;
  6. @Configuration
  7. public class ThreadPoolTaskConfig {
  8. /**
  9. * 默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,
  10. * 当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
  11. * 当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝
  12. */
  13. /**
  14. * 核心线程数(默认线程数)
  15. */
  16. private static final int corePoolSize = 20;
  17. /**
  18. * 最大线程数
  19. */
  20. private static final int maxPoolSize = 100;
  21. /**
  22. * 允许线程空闲时间(单位:默认为秒)
  23. */
  24. private static final int keepAliveTime = 10;
  25. /**
  26. * 缓冲队列大小
  27. */
  28. private static final int queueCapacity = 200;
  29. /**
  30. * 线程池名前缀
  31. */
  32. private static final String threadNamePrefix = "Async-Service-";
  33. @Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
  34. public ThreadPoolTaskExecutor taskExecutor() {
  35. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  36. executor.setCorePoolSize(corePoolSize);
  37. executor.setMaxPoolSize(maxPoolSize);
  38. executor.setQueueCapacity(queueCapacity);
  39. executor.setKeepAliveSeconds(keepAliveTime);
  40. executor.setThreadNamePrefix(threadNamePrefix);
  41. // 线程池对拒绝任务的处理策略
  42. // CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
  43. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  44. // 初始化
  45. executor.initialize();
  46. return executor;
  47. }
  48. }