【怎么设置核心线程数也可以被回收?】
要设置核心线程数也可以被回收,可以使用以下两种方式:
使用ThreadPoolExecutor类中的allowCoreThreadTimeOut()方法。
这个方法默认是false,如果将其设置为true,就可以让核心线程数也可以被回收了。示例如下:
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>());
executor.allowCoreThreadTimeOut(true);
自定义ThreadPoolExecutor类,重写beforeExecute()方法和afterExecute()方法,在这两个方法中对核心线程进行回收。
示例如下:
public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
public CustomThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
if (this.getPoolSize() > this.getCorePoolSize()) {
// 如果当前线程池中线程数大于核心线程数,那么就移除核心线程
this.remove(t);
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (this.getPoolSize() == this.getCorePoolSize()) {
// 如果当前线程池中线程数等于核心线程数,那么就继续执行核心线程
this.prestartCoreThread();
}
}
}
使用自定义的ThreadPoolExecutor类示例如下:
CustomThreadPoolExecutor executor = new CustomThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>());
使用以上两种方式,都可以让核心线程数也可以被回收。
下一篇:
JVM的职责——加载和运行字节码
