這樣可以避免堵塞、以及保證任務的實時性。適用於處理log、發送郵件、短信……等。html
<!-- 缺省的異步任務線程池 --> <task:annotation-driven executor="asyncExecutor" /> <task:executor id="asyncExecutor" pool-size="100-10000" queue-capacity="10" /> <!-- 處理log的線程池 --> <task:executor id="logExecutor" pool-size="15-1000" queue-capacity="5" keep-alive="5"/>
@Override @Async("logExecutor") //假設不指定名字。會使用缺省的「asyncExecutor」 public void saveUserOpLog(TabUserOpLog tabUserOpLog) { userOpLogDAO.insertTabUserOpLog(tabUserOpLog); }(注意:假設在同一個類中調用的話。不會生效,緣由請參考: http://blog.csdn.net/clementad/article/details/47339519)
然而,線程池中已經在執行的任務。由於缺省是用戶線程,因此JVM會等待它們結束後才退出。java
@Configuration @EnableAsync public class SpringConfig { /** Set the ThreadPoolExecutor's core pool size. */ private int corePoolSize = 10; /** Set the ThreadPoolExecutor's maximum pool size. */ private int maxPoolSize = 200; /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */ private int queueCapacity = 10; private String ThreadNamePrefix = "MyLogExecutor-"; @Bean public Executor logExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix(ThreadNamePrefix); // rejection-policy:當pool已經達到max size的時候,怎樣處理新任務 // CALLER_RUNS:不在新線程中運行任務。而是有調用者所在的線程來運行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }