一. 簡介
- Spring通過任務執行器(TaskExecutor)來實現多線程和併發編程;
- 使用TreadlePoolTaskExecutor可實現一個人基於線程池的TaskExecutor;
- 實際開發中任務一般是異步的,可用@EnableAsync開始異步任務的支持,並通過在實際執行的Bean的方法中使用@Async聲明其是一個異步任務。
二. 示例解析
-
配置類
@Configuration @ComponentScan("com.muzi.springboot01.chapter3.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; } }
-
任務執行類
@Service public class AsyncTaskTaskService { @Async public void executorAsyncTask(Integer i) { System.out.println("執行異步任務:"+i); } @Async public void executorAsyncTaskPlus(Integer i) { System.out.println("執行異步任務+1:"+(i+1)); } }
-
運行
public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorconfig.class); AsyncTaskTaskService asyncTaskTaskService = context.getBean(AsyncTaskTaskService.class); for (int i = 0; i < 10; i++) { asyncTaskTaskService.executorAsyncTask(i); asyncTaskTaskService.executorAsyncTaskPlus(i); } context.close(); } }
-
運行結果