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