SpringBoot多執行緒
阿新 • • 發佈:2019-02-17
Springt通過任務執行器(TaskExecutor)來實現多執行緒和併發程式設計。使用ThreadPoolTaskExecutor可實現一個基於執行緒池的TaskExecutor。而實際開發中任務一般是非阻礙的,即非同步的,所以我們要在配置類中通過@EnableAsync 開啟對非同步任務的支援,並通過實際執行Bean的方法中使用@Async註解來宣告其是一個非同步任務。
1、配置類
package com.idark.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 @EnableAsync // 利用@EnableAsync註解開啟非同步任務支援 public class AsyncTaskConfig implements AsyncConfigurer{ @Override public Executor getAsyncExecutor() { // 配置類實現AsyncConfigurer介面並重寫 getAsyncExecutor 方法 // 返回一個ThreadPoolTaskExecutor ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.setQueueCapacity(25); taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
2、任務Service
package com.idark.async; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncTaskService { // 通過@Async註解表明該方法是一個非同步方法,如果註解在類級別,表明該類下所有方法都是非同步方法,而這裡的方法自動被注入使用ThreadPoolTaskExecutor 作為 TaskExecutor @Async public void executeAsyncTask(Integer i){ System.out.println("執行非同步任務:" + i); } @Async public void executeAsyncTaskPlus(Integer i){ System.out.println("執行非同步任務+1:" + (i+1)); } }
3、執行
package com.idark.async; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestMain{ public static void main(String[] args){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class); AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); for(int i = 0; i < 50; i++){ asyncTaskService.executeAsyncTask(i); asyncTaskService.executeAsyncTaskPlus(i); } } }