ThreadPoolExecutor应用程序未完成 [英] ThreadPoolExecutor application does not Finish

查看:83
本文介绍了ThreadPoolExecutor应用程序未完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个超级简单的应用程序会打印"Hello",但不会完成.我绝对没有理由这么做.

This super simple application prints "Hello" but does not finish. I see absolutely no reason why this should be.

JavaDoc ,本节定稿,说

程序中不再引用且没有剩余线程的池将自动关闭.

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

显然没有引用

tpe,这意味着线程没有完成.但是我不明白为什么.有人可以解释吗?

tpe is clearly not referenced, that means that thread does not finish. But I don't understand why. Could someone explain?

在这种情况下,解决方案是在main的末尾调用shutdown(),但是我的实际应用更加复杂.新工作是在Runnable内部生成的,所以我不知道什么时候会处理完所有内容.

Solution in this case is to call shutdown() at the end of main, but my actual application is more complicated. New work is generated inside of Runnables, so I don't know when exactly everything will be processed.

那么,我需要弄清楚何时调用shutdown吗?还是可能以某种方式指定当tpe的队列为空时,它应该自行关闭?

So, do I need to figure out when to call shutdown? Or is it possible to somehow specify that, when tpe's queue is empty, it should shut itself down?

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");
        }
    });
}

}

推荐答案

当您的主要方法完成后,您的执行器将没有任务,但仍有线程在运行.

When your main method finishes your executor has no tasks left, but it still has threads running.

设置标志提交任何任务之前,将allowCoreThreadTimeout 设置为true.然后,当您的执行程序在main方法完成时超出范围并且您的所有任务完成时,线程将被终止.请参见 ThreadPoolExecutor API文档 :

Set the flag 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:

程序中不再引用且没有剩余线程的池将自动关闭.如果即使在用户忘记调用shutdown()的情况下仍要确保收回未引用的池,则必须使用零核心线程的下限和/或通过设置适当的保持存活时间,来安排未使用的线程最终死掉设置allowCoreThreadTimeOut(boolean).

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).

这篇关于ThreadPoolExecutor应用程序未完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆