ThreadPoolTaskConfig.java 2.1 KB

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