单例线程池

该代码示例展示了如何在Java中创建一个线程池,基于CPU核心数动态配置核心线程数和最大线程数。线程池工具类包含执行无返回值任务和有返回值任务的方法,并建议将线程池配置参数移到yaml文件中以实现代码解耦。
摘要由CSDN通过智能技术生成

代码


package com.gdpu.enumeration;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author mojiazhu
 * @date 2022/12/8 21:40
 *
 * 线程池工具类
 */
public enum EnumThreadPool {
    INSTANCE;

    private ThreadPoolExecutor threadPool;

    public ThreadPoolExecutor getInstance() {
        return this.threadPool;
    }

    /**
     * 无返回值直接执行
     */
    public void execute(Runnable runnable) {
        this.threadPool.execute(runnable);
    }

    /**
     * 返回值直接执行
     */
    public <T> Future<T> submit(Callable<T> callable) {
        return this.threadPool.submit(callable);
    }

    EnumThreadPool() {
        //根据cpu的数量动态的配置核心线程数和最大线程数
        int CPU_COUNT = Runtime.getRuntime().availableProcessors();

        //核心线程数 = CPU核心数 + 1
        int CORE_POOL_SIZE = CPU_COUNT + 1;

        //线程池最大线程数 = CPU核心数 * 2 + 1
        int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;

        //非核心线程闲置时超时1s
        int KEEP_ALIVE = 1;

        this.threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS,
                new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE));
    }

}

使用


   EnumThreadPool.INSTANCE.execute(()->{
            System.out.println("登录成功");
        });

建议

我们的线程池配置参数可以放到我们的yaml中去,这样我们就可以通过修改yaml来间接修改线程池,实现代码解耦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚霞虽美不如你

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值