SpringBoot2線程池定義使用方法解析
我們都知道spring只是為我們簡(jiǎn)單的處理線程池,每次用到線程總會(huì)new 一個(gè)新的線程,效率不高,所以我們需要自定義一個(gè)線程池。
定義線程池
@Slf4j@EnableAsync@Configurationpublic class AsyncExecutorConfig implements AsyncConfigurer { @Bean public ThreadPoolTaskExecutor asyncServiceExecutor() { //返回可用處理器的虛擬機(jī)的最大數(shù)量不小于1 int cpu = Runtime.getRuntime().availableProcessors(); log.info('start asyncServiceExecutor cpu : {}', cpu); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //配置核心線程數(shù) executor.setCorePoolSize(cpu); //配置最大線程數(shù) executor.setMaxPoolSize(cpu); //配置隊(duì)列大小 executor.setQueueCapacity(50); //用來(lái)設(shè)置線程池關(guān)閉的時(shí)候等待所有任務(wù)都完成再繼續(xù)銷(xiāo)毀其他的Bean executor.setWaitForTasksToCompleteOnShutdown(true); //設(shè)置線程池中任務(wù)的等待時(shí)間,如果超過(guò)這個(gè)時(shí)候還沒(méi)有銷(xiāo)毀就強(qiáng)制銷(xiāo)毀,以確保應(yīng)用最后能夠被關(guān)閉,而不是阻塞住 executor.setAwaitTerminationSeconds(60); //配置線程池中的線程的名稱前綴 executor.setThreadNamePrefix('async-service-'); // rejection-policy:當(dāng)pool已經(jīng)達(dá)到max size的時(shí)候,如何處理新任務(wù) // CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是有調(diào)用者所在的線程來(lái)執(zhí)行 // 使用預(yù)定義的異常處理類 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //執(zhí)行初始化 executor.initialize(); return executor; } @Override public Executor getAsyncExecutor() { return asyncServiceExecutor(); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return (throwable, method, objects) -> { StringBuilder sb = new StringBuilder(); for (Object param : objects) {sb.append(param).append(','); } log.error('Exception message - {},Method name - {},Parameter value - {}', throwable.getMessage(), method.getName(), sb.toString()); }; }}
如何使用
@Autowired private ThreadPoolTaskExecutor threadPoolTaskExecutor;public void test(){ CompletableFuture<Void> userFuture = CompletableFuture.runAsync(() -> System.out.println(111), threadPoolTaskExecutor);}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. java實(shí)現(xiàn)2048小游戲(含注釋)2. ASP 連接Access數(shù)據(jù)庫(kù)的登陸系統(tǒng)3. phpstudy apache開(kāi)啟ssi使用詳解4. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法5. 網(wǎng)頁(yè)中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測(cè)試)6. python 爬取豆瓣網(wǎng)頁(yè)的示例7. asp知識(shí)整理筆記4(問(wèn)答模式)8. Python實(shí)現(xiàn)播放和錄制聲音的功能9. 如何用python 操作MongoDB數(shù)據(jù)庫(kù)10. AJAX的跨域問(wèn)題解決方案
