Spring中通過任務執行器TaskExecutor來實現多線程和並發編程。
使用ThreadPoolTaskExecutor可實現一個基於線程池的TaskExecutor。
因為實際開發中任務一般是異步的(即非阻塞的),所以要在配置類中@EnableAsync ,並在實際執行的Bean方法中使用@Async來聲明這是一個異步方法。
配置類的實現:
@Configuration
@ComponentScan("com.prac.spring.task_executor")
@EnableAsync //開啟異步任務支持
public class TaskExecutorConfig implements AsyncConfigurer {
//配置類繼承AsyncConfigurer接口並重寫getAsyncExecutor方法,並返回ThreadPoolTaskExecutor,
//這樣我們就獲得了一個基於線程池TaskExecutor
@Override
public Executor getAsyncExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(15);
taskExecutor.setQueueCapacity(30);
taskExecutor.initialize();
return taskExecutor;
}
/**
* AsyncUncaughtExceptionHandler:用來處理從異步方法拋出的未被捕獲的exceptions
* An asynchronous method usually returns a Future instance that gives access to the underlying exception. When the method does not provide that return type, this handler can be used to managed such uncaught exceptions.
*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
return null;
}
}