java - ThreadPoolExecutor 应用程序未完成

标签 java multithreading concurrency java.util.concurrent threadpoolexecutor

这个 super 简单的应用程序打印“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");
        }
    });
}

最佳答案

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

设置标志 allowCoreThreadTimeout在提交任何任务之前为真。然后,当您的执行程序在 main 方法完成时超出范围,并且您的所有任务都完成时,线程将被终止。请参阅 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).

关于java - ThreadPoolExecutor 应用程序未完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30633698/

相关文章:

java - ConditionVariable 防止两个线程同时运行

multithreading - 多个线程之间的数据访问同步

C++ 终端应用程序并发输入和输出

ios - 合并 `NSManagedObjectContextDidSaveNotification` 后 NSFetchedResultsController 未显示所有结果

java - Dijkstra 算法只有一行文件没有正确处理

Java 和日语字符

c++ - future 是检查单个线程完成的安全方法吗?

c++ - c++ 11中的线程安全对象状态操作

ruby-on-rails - 如何确保模型始终使用事务和锁(在 Rails 中)?

java - 尝试了解 Java 枚举中函数的用法