线程池使用

AtomicLong total = new AtomicLong();
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("同步培训记录-");
threadPoolTaskExecutor.setCorePoolSize(cpuNum);
threadPoolTaskExecutor.setMaxPoolSize(cpuNum * 2);
threadPoolTaskExecutor.setQueueCapacity(1000);
threadPoolTaskExecutor.setKeepAliveSeconds(300);
threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
threadPoolTaskExecutor.initialize();
Long count = trainingRecordService.count(new TrainingRecord());
while (total.get() <= count){
    threadPoolTaskExecutor.execute(() -> {
        if (total.get() > count){return;}
        List<TrainingRecord> list = trainingRecordService.listFromHana(new TrainingRecord(), pageNum.get(), pageSize);
        //查询部门信息
        int size = list.size();
        long before = total.getAndAdd(size);
        if (total.get() > count){
            list = null;
            total.set(before);
            return;
        }
        list = initDept(list);
        pageNum.getAndIncrement();
        trainingRecordService.batchInsert(list);
        list = null;
    });
}
threadPoolTaskExecutor.shutdown();

使用 Spring 内部线程池时,一定要手动自定义线程池,配置合理的参数,不然会出现生产问题(一个请求创建一个线程)。

@Configuration
@EnableAsync
public class ThreadPoolExecutorConfig {

    @Bean(name="threadPoolExecutor")
    public Executor threadPoolExecutor(){
        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
        int processNum = Runtime.getRuntime().availableProcessors(); // 返回可用处理器的Java虚拟机的数量
        int corePoolSize = (int) (processNum / (1 - 0.2));
        int maxPoolSize = (int) (processNum / (1 - 0.5));
        threadPoolExecutor.setCorePoolSize(corePoolSize); // 核心池大小
        threadPoolExecutor.setMaxPoolSize(maxPoolSize); // 最大线程数
        threadPoolExecutor.setQueueCapacity(maxPoolSize * 1000); // 队列程度
        threadPoolExecutor.setThreadPriority(Thread.MAX_PRIORITY);
        threadPoolExecutor.setDaemon(false);
        threadPoolExecutor.setKeepAliveSeconds(300);// 线程空闲时间
        threadPoolExecutor.setThreadNamePrefix("test-Executor-"); // 线程名字前缀
        return threadPoolExecutor;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值