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配置文件读取方式