一、问题复现:
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.execute(() -> System.out.println("test"));
}
当任务执行完成后,JVM并没有退出,程序阻塞了。
所以有几个疑问:
1.任务执行完成后,进程为什么没有结束
2.JVM进程什么时候退出
3.此程序为什么会阻塞,在哪个地方阻塞了
二、JVM退出的几种情况
1.没有非守护线程存活2.执行kill -9 强制杀死进程3.java.lang.System.exit(int status)
三、分析当前场景的JVM未退出属于哪种情况
查看源码:
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters and default thread factory and rejected execution handler.
* It may be more convenient to use one of the {@link Executors} factory
* methods instead of this general purpose constructor.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @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.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
根据corePoolSize发现核心线程并不会超时,除非 allowCoreThreadTimeOut 设置true,当前场景应该属于没有非守护线程存活。
我们可以验证一下我们的猜想:
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10,
2L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.allowCoreThreadTimeOut(true);
threadPoolExecutor.execute(() -> System.out.println("test"));
}
发现,在执行完成两秒后,JVM退出。