Executors.newSingleThreadExecutor() 的退出策略是什么
我对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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
newSingleThreadExecutor
返回一个ExecutorService
,它使用单个线程 - 它仍然可以执行多个任务。它不会退出,因为您可能想要提供更多任务。您可以使用:
在任务执行后将其关闭。
newSingleThreadExecutor
returns anExecutorService
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:
to shut it down after the task has executed.
线程保持活动状态,因为它的生命周期与分配给执行程序的任务的生命周期无关;看一下:
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.