Executors.newSingleThreadExecutor() 的退出策略是什么

发布于 2024-12-03 13:20:47 字数 235 浏览 0 评论 0原文

我对java并发很陌生,所以这可能是一个已经回答过很多次的问题,或者太明显了,我可能遗漏了一些东西。

我像这样作为任务运行:

Executors.newSingleThreadExecutor().execute(task)

我的问题是,当任务的 run 方法执行结束时,为什么它不退出或者为什么线程仍然存在?我的理解是,一旦线程 run() 完成,线程就不再存在,对吧?

I'm new to java concurrency so this may be a question already answered many time over or too obvious that I maybe missing something.

I am running as task like so:

Executors.newSingleThreadExecutor().execute(task)

My question is when its comes to end of executing the run method of task why does it not exit or why is the thread still alive? My understanding was once a threads run() completes the thread is no more and ceases to exist, right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痴者 2024-12-10 13:20:47

newSingleThreadExecutor 返回一个 ExecutorService,它使用单个线程 - 它仍然可以执行多个任务。它不会退出,因为您可能想要提供更多任务。

您可以使用:

ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(task);
service.shutdown();

在任务执行后将其关闭。

newSingleThreadExecutor returns an ExecutorService which uses a single thread - it can still execute multiple tasks. It doesn't exit because you may want to supply more tasks.

You can use:

ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(task);
service.shutdown();

to shut it down after the task has executed.

浸婚纱 2024-12-10 13:20:47

线程保持活动状态,因为它的生命周期与分配给执行程序的任务的生命周期无关;看一下:

javadoc for Executors.newSingleThreadExecutor

您会发现,在内部,返回的 ExecutorService 使用单个线程按顺序运行您分配给它的尽可能多的任务,可能如果您的任务之一杀死了原始线程,则实例化一个新线程。

the thread remains alive because its lifecycle is not tied to that of the tasks assigned to the executor; take a look at:

javadoc for Executors.newSingleThreadExecutor

you'll find that internally, the returned ExecutorService uses a single thread to sequentially run as many tasks as you assign to it, potentially instantiating a new thread if one of your tasks kills the original one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文