实现说明
allowCoreThreadTimeOut 空闲回收核心线程以类 ElasticCorePool为骨架。
本示例的循环部分是 for (int i = 0; i < 5; i++)。
使用要点
- 直接运行文件,输出会带上标签,比如
prestarted:、pool size before work:、task——输出的每一行都能指回产生它的那次调用。
常见问题
运行「allowCoreThreadTimeOut 空闲回收核心线程」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 prestarted:、pool size before work:、task 这类标签。
核心语句
Thread.currentThread().interrupt();
pool.allowCoreThreadTimeOut(true);
Thread.sleep(100);
代码示例
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ElasticCorePool {
public static void main(String[] args) throws InterruptedException {
// 核心 2、上限 6;allowCoreThreadTimeOut 要求 keep-alive > 0
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, 6, 300, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
// prestartAllCoreThreads:立刻把核心线程拉起来等活,而不是等第一个任务
System.out.println("prestarted: " + pool.prestartAllCoreThreads());
System.out.println("pool size before work: " + pool.getPoolSize());
// 默认核心线程常驻;打开后空闲的核心线程也按 keep-alive 超时退出
pool.allowCoreThreadTimeOut(true);
for (int i = 0; i < 5; i++) {
final int id = i;
pool.execute(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("task " + id + " done");
});
}
pool.shutdown();
pool.awaitTermination(2, TimeUnit.SECONDS);
// 任务跑完后继续空闲超过 keep-alive:核心线程也退出,池缩到 0
Thread.sleep(600);
System.out.println("pool size after idle: " + pool.getPoolSize());
}
}