打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
SpringBoot2 线程池的定义和使用

SpringBoot2 线程池的定义和使用

定义线程池

@Slf4j@EnableAsync@Configurationpublic class AsyncExecutorConfig implements AsyncConfigurer {    @Bean    public ThreadPoolTaskExecutor asyncServiceExecutor() {        //返回可用处理器的虚拟机的最大数量不小于1        int cpu = Runtime.getRuntime().availableProcessors();        log.info("start asyncServiceExecutor cpu : {}", cpu);        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();        //配置核心线程数        executor.setCorePoolSize(cpu);        //配置最大线程数        executor.setMaxPoolSize(cpu);        //配置队列大小        executor.setQueueCapacity(50);        //用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean        executor.setWaitForTasksToCompleteOnShutdown(true);        //设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住        executor.setAwaitTerminationSeconds(60);        //配置线程池中的线程的名称前缀        executor.setThreadNamePrefix("async-service-");        // rejection-policy:当pool已经达到max size的时候,如何处理新任务        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行        // 使用预定义的异常处理类        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());        //执行初始化        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);}

赵小胖个人博客

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
「一」2、Springboot多线程
性能爆表:SpringBoot利用ThreadPoolTaskExecutor批量插入百万级数据实测...
新来了个技术总监:谁使用 @Async 创建线程以后就消失
【十二】springboot整合线程池解决高并发(超详细,保你理解)
Spring Boot线程池的使用心得
编程语言Spring Boot中如何配置线程池拒绝策略,妥善处理好溢出的任务
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服