ThreadPoolTaskConfig.java 2.3 KB

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