SpringBoot2線程池定義使用方法解析
我們都知道spring只是為我們簡單的處理線程池,每次用到線程總會new 一個新的線程,效率不高,所以我們需要自定義一個線程池。
定義線程池
@Slf4j@EnableAsync@Configurationpublic class AsyncExecutorConfig implements AsyncConfigurer { @Bean public ThreadPoolTaskExecutor asyncServiceExecutor() { //返回可用處理器的虛擬機的最大數(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); //配置隊列大小 executor.setQueueCapacity(50); //用來設(shè)置線程池關(guān)閉的時候等待所有任務(wù)都完成再繼續(xù)銷毀其他的Bean executor.setWaitForTasksToCompleteOnShutdown(true); //設(shè)置線程池中任務(wù)的等待時間,如果超過這個時候還沒有銷毀就強制銷毀,以確保應(yīng)用最后能夠被關(guān)閉,而不是阻塞住 executor.setAwaitTerminationSeconds(60); //配置線程池中的線程的名稱前綴 executor.setThreadNamePrefix('async-service-'); // rejection-policy:當(dāng)pool已經(jīng)達到max size的時候,如何處理新任務(wù) // CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是有調(diào)用者所在的線程來執(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);}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
