TaskExecutePool.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package com.fd.thread;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.scheduling.annotation.EnableAsync;
  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  7. import java.util.concurrent.Executor;
  8. import java.util.concurrent.ThreadPoolExecutor;
  9. /**
  10. * Created by owen on 2017/8/29.
  11. */
  12. @Configuration
  13. @EnableAsync
  14. public class TaskExecutePool {
  15. @Value("${spring.task.pool.corePoolSize}")
  16. private int corePoolSize;
  17. @Value("${spring.task.pool.corePoolSize}")
  18. private int maxPoolSize;
  19. @Value("${spring.task.pool.keepAliveSeconds}")
  20. private int keepAliveSeconds;
  21. @Value("${spring.task.pool.queueCapacity}")
  22. private int queueCapacity;
  23. @Bean
  24. public Executor taskExecutor() {
  25. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  26. executor.setCorePoolSize(corePoolSize);
  27. executor.setMaxPoolSize(maxPoolSize);
  28. executor.setQueueCapacity(keepAliveSeconds);
  29. executor.setKeepAliveSeconds(queueCapacity);
  30. executor.setThreadNamePrefix("MyExecutor-");
  31. // rejection-policy:当pool已经达到max size的时候,如何处理新任务
  32. // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
  33. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  34. executor.initialize();
  35. return executor;
  36. }
  37. }