ThreadPoolExecutor 应用程序未完成

ThreadPoolExecutor application does not Finish

这个超级简单的应用程序打印 "Hello" 但没有完成。我完全看不出为什么会这样。

JavaDoc,部分定稿,说

A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically.

tpe 显然没有被引用,这意味着线程没有完成。但我不明白为什么。有人可以解释一下吗?

这种情况的解决方法是在main的最后调用shutdown(),但是我的实际应用比较复杂。新工作在 Runnables 内部生成,所以我不知道什么时候会处理所有内容。

所以,我需要弄清楚什么时候调用关机吗?或者是否可以以某种方式指定,当 tpe 的队列为空时,它应该自行关闭?

public class JavaApplication5 {
public static void main(String[] args) {
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 15, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    tpe.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello");
        }
    });
}

}

或者是否有可能以某种方式指定,当 tpe 的队列为空时,而不是自行关闭? - 不。即使可能,tpe 的队列也会在以下时间为空您首先创建对象,然后关闭。

但是您可以使用 ThreadPoolExecutor.getActiveCount() 了解当前有多少个线程 运行。如果它达到 0 并在那里停留一段时间,您可以关闭执行程序。

当您的 main 方法完成时,您的执行程序没有 任务 剩余,但它仍有线程 运行.

设置标志allowCoreThreadTimeout to true before submitting any tasks. Then when your executor goes out of scope as the main method finishes, and all your tasks finish, the threads will be terminated. See Finalization in the ThreadPoolExecutor API documentation:

A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically. If you would like to ensure that unreferenced pools are reclaimed even if users forget to call shutdown(), then you must arrange that unused threads eventually die, by setting appropriate keep-alive times, using a lower bound of zero core threads and/or setting allowCoreThreadTimeOut(boolean).