问题描述
这个超级简单的应用程序会打印"Hello",但不会完成.我绝对没有理由这么做.
This super simple application prints "Hello" but does not finish. I see absolutely no reason why this should be.
JavaDoc ,本节定稿,说
显然没有引用
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:
这篇关于ThreadPoolExecutor应用程序未完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!