1. 建造者模式
需求: 使用建造者模式实现ThreadPoolBuilder
要求:
1.常驻线程数 corePoolSize >0
2.最大线程数maximumPoolSize必须 > 常驻线程数
3.空闲线程存活时间keepAliveTime必须>1000
要点:
1.在目标类中创建静态内部类Builder
2.Builder对外暴露的setter方法都需要返回this达到链式调用效果
3.私有化目标类的构造函数
4.在私有化的构造函数中使用Builder的属性来填充目标类的属性
5.编写buil方法来返回目标类,因为build是链式调用的最后一环,所以可以做参数、约束等校验
public class ThreadPoolConfig {
// 常驻线程数量
private int corePoolSize;
// 池中最大线程数量
private int maximumPoolSize;
// 空闲线程存活时间
private long keepAliveTime;
// 私有化构造函数让外部不能new这个配置类, 使用build的属性来填充ThreadPoolConfig的属性
private ThreadPoolConfig(Builder builder){
corePoolSize = builder.corePoolSize;
maximumPoolSize = builder.maximumPoolSize;
keepAliveTime = builder.keepAliveTime;
}
// 构造一个builder,
public static class Builder{
private int corePoolSize;
private int maximumPoolSize;
private long keepAliveTime;
// builder对外暴露三个setter方法
public Builder corePoolSize(int corePoolSize) {
if (corePoolSize <= 0) {
throw new IllegalArgumentException("...");
}
this.corePoolSize = corePoolSize;
return this;
}
public Builder maximumPoolSize(int corePoolSize) {
if (maximumPoolSize <= 0) {
throw new IllegalArgumentException("...");
}
this.maximumPoolSize = corePoolSize;
return this;
}
public Builder keepAliveTime(int corePoolSize) {
if (keepAliveTime <= 0) {
throw new IllegalArgumentException("...");
}
this.keepAliveTime = corePoolSize;
return this;
}
// builder提供一个build方法
public ThreadPoolConfig build(){
// build方法在链式调用的最后一环, 在build里做参数校验,约束限定校验等
if (corePoolSize <= 0){
throw new IllegalArgumentException("...");
}
if (maximumPoolSize < corePoolSize){
throw new IllegalArgumentException("...");
}
if (keepAliveTime < 1000){
throw new IllegalArgumentException("...");
}
return new ThreadPoolConfig(this);
}
}
}
ThreadPoolConfig pool = new Builder()
.keepAliveTime(1000)
.corePoolSize(10)
.maximumPoolSize(100)
.build();