久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

SpringBoot2線程池定義使用方法解析

瀏覽:4日期:2023-05-27 08:20:31

我們都知道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)。

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 苍梧县| 牡丹江市| 威海市| 嵊泗县| 正宁县| 朝阳区| 威信县| 托克逊县| 宣威市| 尼木县| 济宁市| 昌黎县| 张家界市| 乌鲁木齐县| 浮山县| 同仁县| 普兰店市| 镇原县| 湟中县| 利辛县| 泸定县| 克什克腾旗| 古丈县| 镇宁| 望都县| 思南县| 剑川县| 色达县| 遂溪县| 紫金县| 孟津县| 建瓯市| 辽阳县| 丰原市| 沈丘县| 侯马市| 江陵县| 革吉县| 武义县| 突泉县| 绵阳市|