线程池常规使用 以及 基本的信息

第一种 (详细代码可见检修计划断面文件多天生成方法)

步骤一: 在Application启动类 配置线程池的Bean

    在启动类上添加 启用异步注解
    @EnableAsync

    @Bean(name = "sectionalFileServiceExecutors")
    public Executor sectionalFileServiceExecutors() {
        int corePoolSize = 32;
        int maximumPoolSize = 64;
        long keepAliveTime = 30;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(200);
       // 自定义线程 名称 便于查看调试
        ThreadFactory threadFactory = new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, "sectional-file-pool-" + threadNumber.getAndIncrement());
                thread.setDaemon(false);
                return thread;
            }
        };
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        return threadPoolExecutor;
    }


    /**
     * 泛型实体类深拷贝 工具方法
     *
     * @param object
     * @return: T
     * @Author: zhangKangLe
     * @Date: 2024/10/21 14:13
     */
    public static <T> T deepCopy(T object) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (T) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException("Deep copy failed", e);
        }
    }


步骤二: 控制层 ( execute 方法启动是没有返回值的)

    // 依赖注入
    @Autowired
    Executor asyncServiceExecutor;


    @PostMapping("/***********************")
    public Result generateTypicalSection_Executor(@RequestBody SectionalFileBO sectionalFileBO) {

        String startTime = sectionalFileBO.getStartTime();
        String endTime = sectionalFileBO.getEndTime();
        List<String> dateList = generateDateRange(startTime, endTime, "yyyy-MM-dd");

        for (String dataDate : dateList) {
            asyncServiceExecutor.execute(() -> {
                SectionalFileBO itemEntity = deepCopy(sectionalFileBO);
                itemEntity.setDataDate(dataDate);
                sectionFileGenerationService.generateTypicalSection_Executor(itemEntity);
            });
        }

        return Result.success("典型断面生成 成功");
    }


步骤三:配置 ThreadPoolExecutorConfig 类
@Configuration
@EnableAsync
@Slf4j
public class ThreadPoolExecutorConfig {
    /**
     * 核心线程数(默认线程数)
     */
    private int corePoolSize = 32;
    /**
     * 最大线程数
     */
    private int maxPoolSize = 64;
    /**
     * 允许线程空闲时间(单位:默认为秒)
     */
    private static final int keepAliveTime = 60;
    /**
     * 缓冲队列大小
     */
    private int queueCapacity = 200;

    @Bean("asyncServiceTaskExecutor")
    public Executor asyncServiceTaskExecutor() {
        log.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置空闲时间
        executor.setKeepAliveSeconds(keepAliveTime);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程前缀名
        executor.setThreadNamePrefix("async-service-");

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        execu
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值