不建议直接使用Spring的@Async

@Async 中关于线程池的使用部分在 AsyncExecutionInterceptor 中,在这个类中有一个 getDefaultExecutor 方法,当我们没有做过自定义线程池的时候,就会用 SimpleAsyncTaskExecutor 这个线程池。

@Override
protected Executor getDefaultExecutor(BeanFactory beanFactory) {
Executor defaultExecutor = super.getDefaultExecutor(beanFactory);
return (defaultExecutor != null ? defaultExecutor : new SimpleAsyncTaskExecutor());
}

SimpleAsyncTaskExecutor 这玩意坑很大,其实他并不是真的线程池,它是不会重用线程的,每次调用都会创建一个新的线程,也没有最大线程数设置。并发大的时候会产生严重的性能问题。

他的doExecute核心逻辑如下:

/**
* Template method for the actual execution of a task.
* <p>The default implementation creates a new Thread and starts it.
* @param task the Runnable to execute
* @see #setThreadFactory
* @see #createThread
* @see java.lang.Thread#start()
*/
protected void doExecute(Runnable task) {
Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));
thread.start();
}

所以,我们应该自定义线程池来配合@Async使用,而不是直接就用默认的