1.自定义可监控线程池

  1. @Bean("xyThreadPoolTaskExecutor")
  2. public ThreadPoolExecutor threadPoolExecutor() {
  3. return new ThreadPoolExecutor(20, 30, 10, TimeUnit.MINUTES, new ArrayBlockingQueue(10), new AbortPolicy()) {
  4. @Override
  5. protected void beforeExecute(Thread t, Runnable r) {
  6. int poolSize = this.getPoolSize();
  7. System.out.println("poolSize-->" + poolSize);
  8. // TODO 监控内容
  9. super.beforeExecute(t, r);
  10. }
  11. @Override
  12. protected void afterExecute(Runnable r, Throwable t) {
  13. // TODO 监控内容
  14. super.afterExecute(r, t);
  15. }
  16. };
  17. }

2.开启异步功能

  1. @EnableAsync

3.使用线程池异步执行

  1. @Slf4j
  2. @Service
  3. public class AsyncServiceImpl implements AsyncService {
  4. @Override
  5. @Async("xyThreadPoolTaskExecutor")
  6. public void test(String name) {
  7. String message = MessageFormat.format("threadId-:{0},threadName-:{1},call:{2}", Thread.currentThread().getId(), Thread.currentThread().getName(), name);
  8. log.info("3333333...start.." + message);
  9. try {
  10. TimeUnit.SECONDS.sleep(10);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. log.info("3333333...end.." + message);
  15. }
  16. }