Executors.newSingleThreadExecutor 服务是否需要使用关机进行清理?

Does Executors.newSingleThreadExecutor service needs a cleanup using shutdown?

关于使用 newSingleThreadExecutor 清理执行程序服务,我有点困惑。根据其实现,它在内部创建一个线程池,如果失败,将创建一个新线程。我正在使用 singleThreadExecutor,因为我想按顺序 运行 在 运行 时间创建的任务。所以我担心的是,当系统中没有更多任务时,我是否需要关闭此执行程序服务?

我了解到 ExecutorService 中的活动线程会阻止 JVM 关闭。由于singleThreadExecutor在里面也创建了一个线程池,那是不是说明线程是活跃的还是不活跃的呢?

抱歉,如果已经有关于它的问题。

it internally creates a thread pool of one thread

正确

in case of failure a new one will be created

它捕获所有 Throwable,因此当您首先遇到错误时它不会失败。

So my concern is do I need to shutdown this executor service, when there are no more tasks in the system?

如果您担心资源不足,您应该关机。如果您的线程是守护线程,它不会阻止 JVM 关闭(默认情况下它将是非守护线程。

I have read that the active threads inside the ExecutorService prevents the JVM from shutting down.

只有非守护线程才能阻止 JVM 关闭。

Since singleThreadExecutor also creates a thread pool inside, so does that mean that the thread is active or not?

它在处理某事时会处于活动状态。是否激活不改变JVM是否关闭,只改变线程是否是守护进程。

您可以通过提供线程工厂使线程成为守护线程。我建议您这样做,即使您所做的只是设置名称,因为这会使 debugging/profiling 您的应用程序更容易。

这是我之前写的例子NamedThreadFactory