国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

實例講解spring boot 多線程

瀏覽:101日期:2023-08-29 14:53:00

Spring 通過任務執行器(TaskExecutor)來實現多線程和并發編程。使用ThreadPoolTaskExecutor可實現一個基于線程池的TaskExecutor。而實際開發中任務一般是非阻塞的,即異步的,所有我們在配置類中通過@EnableAsync開啟對異步任務的支持,并通過在實際執行的Bean的方法中使用@Async注解來聲明其是一個異步任務。

一、配置類

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@EnableAsyncpublic 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。

二、任務執行類

package com.cenobitor.taskxecutor.taskservice;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;@Servicepublic 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。

如果在異步方法所在類中調用異步方法,將會失效;

三、運行

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 多線程的資料請關注好吧啦網其它相關文章!

標簽: Spring
相關文章:
主站蜘蛛池模板: 织金县| 景东| 子洲县| 海安县| 高台县| 巴里| 墨玉县| 德令哈市| 黄冈市| 年辖:市辖区| 双牌县| 高淳县| 资中县| 昆明市| 平武县| 克什克腾旗| 罗源县| 延川县| 新乡县| 凤山市| 淮北市| 德令哈市| 镇沅| 军事| 精河县| 香格里拉县| 济宁市| 通城县| 会泽县| 桐城市| 太仆寺旗| 乌拉特中旗| 株洲县| 东乡县| 大化| 宜兴市| 义乌市| 亳州市| 乐至县| 子长县| 兴义市|