Springboot中使用多線程

Spring是通過(guò)任務(wù)執(zhí)行器(TaskExecutor)來(lái)實(shí)現(xiàn)多線程和并發(fā)編程,使用ThreadPoolTaskExecutor來(lái)創(chuàng)建一個(gè)基于線城池的TaskExecutor。在使用線程池的大多數(shù)情況下都是異步非阻塞的。我們配置注解@EnableAsync可以開(kāi)啟異步任務(wù)。然后在實(shí)際執(zhí)行的方法上配置注解@Async上聲明是異步任務(wù)。
                                        ------摘抄自書(shū)籍《JavaEE開(kāi)發(fā)的顛覆者 Spring Boot實(shí)戰(zhàn) 》

關(guān)鍵代碼:
配置類(lèi)代碼:
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    //核心線程數(shù)
    taskExecutor.setCorePoolSize(20);
    //最大線程數(shù)
    taskExecutor.setMaxPoolSize(40);

    taskExecutor.setQueueCapacity(100);
    executor.setKeepAliveSeconds(60);
    executor.setThreadNamePrefix("taskExecutor-");
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.setAwaitTerminationSeconds(60);
    taskExecutor.initialize();
    return taskExecutor;
}

}

任務(wù)執(zhí)行代碼:

@Servicepublic class AsyncService {
@Async
public void executeAsync() {
//業(yè)務(wù)邏輯代碼
......
}
}

通過(guò)@Async注解表明該方法是異步方法,如果注解在類(lèi)上,那表明這個(gè)類(lèi)里面的所有方法都是異步的。這里的方法自動(dòng)被注入使用配置的ThreadPoolTaskExecutor作為T(mén)askExecutor。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容