ThreadPoolTaskConfig.java 2.2 KB

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