参数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
- int corePoolSize 核心线程数(随时就绪的状态)
- int maximumPoolSize 最大线程数(极限情况下,线程池最多有多少线程)
- long keepAliveTime 空闲线程存活时间(非核心线程在无任务情况下要多久释放)
- TimeUnit unit 空闲线程存活时间的单位:分钟和秒
- BlockingQueue<Runnable> workQueue 工作队列(用于存放线程执行任务)
- ThreadFactory threadFactory 线程工程(掌控每个线程的生产和线程的属性,比如线程名)
- RejectedExecutionHandler handler 拒绝策略(任务队列满的时候我们采取的措施,比如抛异常,自定义策略)
配置
配置类
package com.xin.springbootinittemplate.config;
import com.xin.springbootinittemplate.handler.ThreadPoolExecutorFactory;
import com.xin.springbootinittemplate.handler.ThreadPoolExecutorHandler;
import org.springframework.context.annotation.Bean;
import java.util.concurrent.*;
/**
* @Author Retrograde-LX
* @Date 2024/08/07 下午 2:21
* @Version 1.0
* @Remark 又是程序猿秃头的一天
*/
public class ThreadPoolExecutorConfig {
@Bean
public ThreadPoolExecutor threadPoolExecutor(){
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1000);
ThreadFactory threadFactory = new ThreadPoolExecutorFactory();
RejectedExecutionHandler handler = new ThreadPoolExecutorHandler();
return new ThreadPoolExecutor(
5,
10,
60,
TimeUnit.SECONDS,
workQueue,
threadFactory,
handler);
}
}
线程工程:
package com.xin.springbootinittemplate.handler;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.ThreadFactory;
/**
* @Author Retrograde-LX
* @Date 2024/08/07 下午 2:24
* @Version 1.0
* @Remark 又是程序猿秃头的一天
*/
public class ThreadPoolExecutorFactory implements ThreadFactory {
@Override
public Thread newThread(@NotNull Runnable r) {
Thread thread = new Thread(r);
thread.setName("业务的线程名称");
return thread;
}
}
拒绝策略:
package com.xin.springbootinittemplate.handler;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @Author Retrograde-LX
* @Date 2024/08/07 下午 2:26
* @Version 1.0
* @Remark 又是程序猿秃头的一天
*/
public class ThreadPoolExecutorHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// 拒绝策略(也可以利用消息队列来排队处理,或者保存到数据库中再利用定时任务来处理)
System.out.println("Task" + r.toString() + "rejected from" + executor.toString());
}
}
使用
在需要使用的地方注入线程池对象
@Resource
private ThreadPoolExecutor threadPoolExecutor;
调用:
CompletableFuture.runAsync(() -> {
// 业务代码
}, threadPoolExecutor);