zoukankan      html  css  js  c++  java
  • springboot 使用线程池处理多线程任务

    一、创建线程池

    @Configuration
    @EnableAsync
    public class SpringAsyncConfig {

    @Bean("taskExecutor")
    public Executor asyncServiceExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    // 设置核心线程数
    executor.setCorePoolSize(5);
    // 设置最大线程数
    executor.setMaxPoolSize(20);
    //配置队列大小
    executor.setQueueCapacity(Integer.MAX_VALUE);
    // 设置线程活跃时间(秒)
    executor.setKeepAliveSeconds(60);
    // 设置默认线程名称
    executor.setThreadNamePrefix("xcc");
    // 等待所有任务结束后再关闭线程池
    executor.setWaitForTasksToCompleteOnShutdown(true);
    //执行初始化
    executor.initialize();
    return executor;
    }
    }

    二、创建使用线程池的server(网上有人说线程任务最好放到一个server里面不然会造成循环依赖。。。未验证)
    public interface ThreadUtilsService {
    /**
    * 获取用户下的考勤记录
    * @param wechatUser
    */
    void setAttendance(WechatUser wechatUser, CountDownLatch countDownLatch);
    }


    @Service
    public class ThreadUtilsServiceImpl implements ThreadUtilsService {
    @Autowired
    private AttendanceService attendanceService;

    @Async("taskExecutor")
    @Override
    public void setAttendance(WechatUser wechatUser, CountDownLatch countDownLatch) {
    List<Attendance> currentClockListByOpenId = attendanceService.getCurrentClockListByOpenId(wechatUser);
    countDownLatch.countDown();
    wechatUser.setAttendanceList(currentClockListByOpenId);
    }
    }


    三、调用
    threadUtilsService.setAttendance(record,countDownLatch);



  • 相关阅读:
    Mongodb在Linux下的安装和启动和配置
    Java线程--Exchanger使用
    Java线程--Phaser使用
    Java线程--CyclicBarrier使用
    Java线程--CountDownLatch使用
    Java线程状态介绍
    Java8 Stream 的一些操作和介绍
    Java正则
    Linux curl命令进行网络请求
    Netty入门使用教程
  • 原文地址:https://www.cnblogs.com/cw828/p/14926751.html
Copyright © 2011-2022 走看看