大家好,又见面了,我是你们的朋友全栈君。
总结:
线程池类 ThreadPoolExecutor 中已经提供了对应的方法,允许动态修改线程池参数:
1、动态修改核心数
当 allowCoreThreadTimeOut 参数设置为 true 的时候,
核心线程在空闲了 keepAliveTime 的时间后也会被回收的,
相当于线程池自动给你动态修改了
public void setCorePoolSize(int corePoolSize) {
if (corePoolSize < 0)
throw new IllegalArgumentException();
int delta = corePoolSize - this.corePoolSize;
this.corePoolSize = corePoolSize;
if (workerCountOf(ctl.get()) > corePoolSize)
interruptIdleWorkers();
else if (delta > 0) {
int k = Math.min(delta, workQueue.size());
while (k-- > 0 && addWorker(null, true)) {
if (workQueue.isEmpty())
break;
}
}
}
2、动态修改最大线程数
public void setMaximumPoolSize(int maximumPoolSize) {
if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
throw new IllegalArgumentException();
this.maximumPoolSize = maximumPoolSize;
if (workerCountOf(ctl.get()) > maximumPoolSize)
interruptIdleWorkers();
}
3、动态修改存活时间
public void setKeepAliveTime(long time, TimeUnit unit) {
if (time < 0)
throw new IllegalArgumentException();
if (time == 0 && allowsCoreThreadTimeOut())
throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
long keepAliveTime = unit.toNanos(time);
long delta = keepAliveTime - this.keepAliveTime;
this.keepAliveTime = keepAliveTime;
if (delta < 0)
interruptIdleWorkers();
}
4、动态修改线程工厂
public void setThreadFactory(ThreadFactory threadFactory) {
if (threadFactory == null)
throw new NullPointerException();
this.threadFactory = threadFactory;
}
5、动态修改拒绝策略
public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
if (handler == null)
throw new NullPointerException();
this.handler = handler;
}
6、可以发现是没有提供方法修改线程队列的,这是因为线程队列的 capacity 参数被 final 所修饰了
private final int capacity;
但是我们可以自定义线程队列,然后把 capacity 参数去掉 final 修饰即可。
操作起来也非常方便,把 LinkedBlockingQueue 粘贴一份出来,修改个名字,
然后把 capacity 参数的 final 修饰符去掉,并提供其对应的 get/set 方法
private volatile int capacity;
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/134967.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...