没有引用指向且没有剩余线程的线程池将会自动关闭。
看一下线程池的构造方法
/**
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* 核心线程数:即使是空闲状态也可以在线程池存活的线程数量,除非
* allowCoreThreadTimeOut 设置为 true。
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* 存活时间:对于超出核心线程数的线程,空闲时间一旦达到存活时间,就会被销毁。
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) { ... ... }
这里我们只关心与线程存活状态最紧密相关的两个参数,也就是corePoolSize和keepAliveTime,上述代码块也包含了这两个参数的源码注释和中文翻译。keepAliveTime参数指定了非核心线程的存活时间,非核心线程的空闲时间一旦达到这个值,就会被销毁,而核心线程则会继续存活,只要有线程存活,线程池也就不会自动关闭。
那么我们将核心线程数设置成0, 设置非核心线程存活时间, 当所有非核线程空闲时间到达指定的存活时间, 会消亡, 那么线程池就会自动关闭了
private static ThreadPoolExecutor EXECUTOR =
new ThreadPoolExecutor(0, 50, 5L, TimeUnit.MINUTES, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());