ThreadPoolTaskConfig.java 2.2 KB

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