美文网首页
SpringBoot中线程池的简单使用

SpringBoot中线程池的简单使用

作者: vincent_wujia | 来源:发表于2020-04-18 11:39 被阅读0次

    SpringBoot是一款很强大的框架

    1. 我们先配置核心线程池核心文件
    @Configuration
    @EnableAsync
    public class BeanConfig {
        @Bean
        public TaskExecutor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            // 设置核心线程数
            executor.setCorePoolSize(3);
            // 设置最大线程数
            executor.setMaxPoolSize(5);
            // 设置队列容量
            executor.setQueueCapacity(10);
            // 设置线程活跃时间(秒)
            executor.setKeepAliveSeconds(60);
            // 设置默认线程名称
            executor.setThreadNamePrefix("hello-");
            // 设置拒绝策略
            executor.setRejectedExecutionHandler(new BeanConfig.MyIgnorePolicy());
            System.out.println("当前核心线程数:" + executor.getCorePoolSize());
            System.out.println("当前线程池最大线程数:"+ executor.getMaxPoolSize());
            System.out.println("获取线程池数:" + executor.getPoolSize());
            System.out.println("线程名称:"+ executor.getThreadNamePrefix());
    
            // 等待所有任务结束后再关闭线程池
            executor.setWaitForTasksToCompleteOnShutdown(true);
            return executor;
        }
    
        /**
         * 线程拒绝策略
         */
        public static class MyIgnorePolicy implements RejectedExecutionHandler {
    
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                doLog(r, e);
            }
    
            private void doLog(Runnable r, ThreadPoolExecutor e) {
                // 可做日志记录等
                System.err.println("这个线程被拒绝了:" + r.toString() );
    //          System.out.println("completedTaskCount: " + e.getCompletedTaskCount());
            }
        }
    }
    

    ThreadPoolExecutorThreadPoolTaskExecutor里面的一些参数配置大体相同(本人是先学习使用ThreadPoolExecutor使用线程池的),[参数配置详情见 菜菜聊架构]这篇博客还不错(https://www.cnblogs.com/caicz/p/10930461.html)
    )
    这里你也可以自定义拒绝策略
    坑边闲话:这里我们使用的是ThreadPoolTaskExecutor来创建线程,在下一篇我会使用ThreadPoolExecutor创建线程,就目前根据阿里规范而言我们是不推荐使用newCachedThreadPool创建一个可缓存线程池、newFixedThreadPool创建一个定长线程池、newScheduledThreadPool创建一个定长线程池、newSingleThreadExecutor创建一个单线程化的线程池这四种方式创建线程的

    2 . 配置完成线程池后我们就可以开始使用线程池了
    我们先编写控制层

    @RestController
    @RequestMapping("/threadController")
    public class ThreadController {
    
        @Autowired
        private AsyncService asyncService;
    
        @GetMapping("/testThread")
        public String testThread() {
            //调用service层的任务
            asyncService.executeAsync();
            return "执行开始";
        }
    
    }
    

    编写业务层接口类

    public interface AsyncService {
        /**
         * 调用线程池
         **/
        void executeAsync();
    }
    

    最后编写业务层接口实现类

    @Service
    public class AsyncServiceImpl implements AsyncService {
    
        private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);
        /**
         * 这里必须使用@Async注解否者你就没有调用线程池里的线程
         * 在@Async("")中里面需要填写在核心配置里面的方法名(即添加了@Bean注解的方法名且一致)
         **/
        @Async("taskExecutor")
        @Override
        public void executeAsync() {
            logger.info("开始线程任务");
            try {
                //这里编写循环是为了测试当前线程池,当线程池达到最大容量时线程池会调用拒绝策略
                int num = 100;
                for (int i=1;i<=num;i++){
                    System.out.println("!!!!当前运行的线程名称:" + Thread.currentThread().getName());
                    Thread.sleep(3000L);
                    System.out.println("当前次数:" + i);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("结束线程任务");
        }
    }
    

    根据自己的需求可以自定义配置线程池大小,拒绝策略等配置
    至此SpringBoot简单使用线程池就写完了,如有不懂可以加SpringBoot技术交流群14群号:719099151我是小吾,有问题可以直接在群里@我

    相关文章

      网友评论

          本文标题:SpringBoot中线程池的简单使用

          本文链接:https://www.haomeiwen.com/subject/dromvhtx.html