一. 點睛
Spring通過任務執行器(TaskExecutor)來實現多線程和並發編程。使用ThreadPoolTaskExecutor可實現一個基於線程池的TaskExecutor。而實際開發中任務一般是非阻礙的,即異步的,所以我們要在配置類中通過@EnableAsync開啟對異步任務的支持,並通過在實際執行的Bean的方法中使用@Async注解來聲明其是一個異步任務。
二. 示例
1. 配置類
package org.light4j.sping4.senior.taskExecutor;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@ComponentScan("org.light4j.sping4.senior.taskExecutor")
@EnableAsync //①
public class TaskExecutorConfig implements AsyncConfigurer{//②
@Override
public Executor getAsyncExecutor() {//②
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
代碼解釋:
① 利用@EnableAsync注解開啟異步任務支持。
② 配置類實現AsyncConfigurer接口並重寫getAsyncExecutor方法,並返回ThreadPoolTaskExecutor ,這樣就獲得了一個基於線程池的TaskExecutor。
2. 任務執行類
package org.light4j.sping4.senior.taskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
@Async //①
public void executeAsyncTask(Integer i){
System.out.println("執行異步任務: "+i);
}
@Async
public void executeAsyncTaskPlus(Integer i){
System.out.println("執行異步任務+1: "+(i+1));
}
}
代碼解釋:
① 通過@Async注解表明該方法是個異步方法,如果注解在類級別,則表明該類所有的方法都是異步方法,而這里的方法自動被注入使用ThreadPoolTaskExecutor作為TaskExecutor。
3. 運行
package org.light4j.sping4.senior.taskExecutor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
for(int i =0 ;i<10;i++){
asyncTaskService.executeAsyncTask(i);
asyncTaskService.executeAsyncTaskPlus(i);
}
context.close();
}
}
輸出結果表明是並發執行而不是順序執行的,
運行結果如下圖所示:
4. 源代碼示例:
