Spring 通過任務執行器(TaskExecutor)來實現多線程和并發編程。使用ThreadPoolTaskExecutor可實現一個基于線程池的TaskExecutor。而實際開發中任務一般是非阻塞的,即異步的,所有我們在配置類中通過@EnableAsync開啟對異步任務的支持,并通過在實際執行的Bean的方法中使用@Async注解來聲明其是一個異步任務。
一、配置類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package com.cenobitor.taskxecutor.config; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; 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 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 ; } } |
1、利用@EnableAsync注解開啟異步任務支持
2、配置類實現AsyncConfigurer接口并重寫getAsyncExecutor方法,并返回一個ThreadPoolTaskExecutor,這樣我們就獲得了一個基于線程池TaskExecutor。
二、任務執行類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package com.cenobitor.taskxecutor.taskservice; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncTaskService { @Async public void excuteAsyncTask(Integer i){ System.out.println( "異步執行任務:" +i); } @Async public void excuteAsyncTaskPlus(Integer i){ System.out.println( "異步執行任務+1:" +(i+ 1 )); } } |
通過@Async注解表明該方法是異步方法,如果注解在類級別,則表明該類所有的方法都是異步方法,而這里的方法自動被注入使用ThreadPoolTaskExecutor作為TaskExecutor。
如果在異步方法所在類中調用異步方法,將會失效;
三、運行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.cenobitor.taskxecutor; import com.cenobitor.taskxecutor.taskservice.AsyncTaskService; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskxecutorApplication. class ); AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService. class ); for ( int i = 0 ; i < 10 ; i++) { asyncTaskService.excuteAsyncTask(i); asyncTaskService.excuteAsyncTaskPlus(i); } context.close(); } } |
運行結果:
異步執行任務:0
異步執行任務+1:1
異步執行任務:1
異步執行任務+1:2
異步執行任務:2
異步執行任務:3
異步執行任務:5
異步執行任務+1:6
異步執行任務:6
異步執行任務+1:7
異步執行任務:7
異步執行任務+1:8
異步執行任務:8
異步執行任務+1:9
異步執行任務:9
異步執行任務+1:10
異步執行任務+1:3
異步執行任務:4
異步執行任務+1:5
異步執行任務+1:4
注:摘抄自《JavaEE開發的顛覆者SpringBoot 實戰》。
以上就是實例講解spring boot 多線程的詳細內容,更多關于spring boot 多線程的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/gdwkong/p/9311047.html