线程池(多线程)工具类及使用

1.定义(Ctrl+C / V)线程池(多线程)工具类

2.使用多线程。

3.按需修改线程配置,以及拒绝策略

以下正文:

线程池(多线程)工具类示例代码

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;

/**
 * 线程池
 * BaseThreadPool
 *
 * @author CloverAn
 **/
@Slf4j
public class BaseThreadPool {
    private volatile static BaseThreadPool baseThreadPool;
    private final ThreadPoolExecutor threadPoolExecutor;

    //核心线程 2
    int corePoolSize = 5;
    //最大数据量 3
    int maxPoolSize = 10;
    //超出核心线程数量的线程存活时间 30秒
    long keepAliveTime = 30;
    //队列
    int capacity = 100;
    
    /**
     * 线程池信息: 核心线程数量1,最大数量3,队列大小10,超出核心线程数量的线程存活时间:30秒, 指定拒绝策略的
     */
    public BaseThreadPool() {
        threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS,
                linkedBlockingQueue, threadFactory, rejectedExecutionHandler);
    }

    /**
     * 阻塞队列,当任务大于线程数,阻塞队列还未满,就会加入阻塞队列中
     */
    LinkedBlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>(capacity);

    /**
     * 管理创建的线程,可以设置线程的名称等属性。
     */
    ThreadFactory threadFactory = r -> {
        Thread t = new Thread(r);
        //设置为守护线程
        t.setDaemon(true);
        return t;
    };

    /**
     * 拒绝策略,当阻塞对面已满,线程达到最大线程,就会采用阻塞策略。
     * 这里就直接输出一个日志了
     */
    RejectedExecutionHandler rejectedExecutionHandler = (r, executor) -> log.info("线程池占用,有任务被拒绝执行了!");

	
    public static BaseThreadPool getThreadPool() {
        if (baseThreadPool == null) {
            synchronized (BaseThreadPool.class) {
                if (baseThreadPool == null) {
                    baseThreadPool = new BaseThreadPool();
                }
            }
        }
        return baseThreadPool;
    }

    public void execute(Runnable task) {
        // 提交任务给线程池执行
        threadPoolExecutor.execute(task);
    }

    public void executeClose() throws Exception {
        // 关闭线程池
        threadPoolExecutor.shutdown();
        threadPoolExecutor.awaitTermination(1, TimeUnit.DAYS);
    }
}

使用多线程代码样例

//注入线程池
 BaseThreadPool threadPoolExecutor = BaseThreadPool.getThreadPool();
//执行多线程
threadPoolExecutor.execute(new Runnable() {
    @Override
    public void run() {
        //业务逻辑
    }
});
//关闭线程池和所有线程
threadPoolExecutor.executeClose();

以上线程执行也可以写为,懂吧懂吧懂吧?

BaseThreadPool threadPoolExecutor = BaseThreadPool.getThreadPool();
threadPoolExecutor.execute(() -> {
	//业务逻辑   
});
threadPoolExecutor.executeClose();

按需修改

那就按需修改吧,比如线程数据提取到配置文件,不会的可以看看我的另外一篇教程。
多种yml/properties配置文件读取方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CloverAn

如果文章对你有帮助,感谢支持!

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

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

打赏作者

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

抵扣说明:

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

余额充值