Java 在运行方法完成后如何清理线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4283270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I cleanup a Thread after its run method finishes?
提问by nath
What should be done with a Thread after its run()
method finishes executing? Is there any cleanup needed for a Thread in Java?
线程的run()
方法执行完成后应该做什么?Java 中的线程是否需要清理?
采纳答案by Jon Skeet
Unless the thread's work has used some unmanaged resources (network streams, files etc) - in which case itshould clean up after itself - there's nothing you need to do.
除非线程的工作使用了一些非托管资源(网络流、文件等)——在这种情况下它应该自行清理——你不需要做任何事情。
Note that holding a reference to the Thread
object representing the thread won't keep the underlying OS thread alive.
请注意,持有对Thread
代表线程的对象的引用不会使底层 OS 线程保持活动状态。
回答by Srinivas Reddy Thatiparthy
You don't need to, thread exits , once run
method finishes it's execution
你不需要,线程退出,一旦run
方法完成它的执行
回答by Jinesh Parekh
Nopes. The thread would execute and die on its own and get garbage collected.
不。该线程将自行执行并死亡并收集垃圾。
回答by vaibought
No its not necessary. When the thread exit its run method, the thread come into exit state itself.
不,这是没有必要的。当线程退出它的 run 方法时,线程本身进入退出状态。
回答by khachik
Generally cleaning up is done by the garbage collector. If the threads uses files/sockets you may need to close them. The best practice is to close resources in the top-level finally
block in Thread::run
.
通常清理是由垃圾收集器完成的。如果线程使用文件/套接字,您可能需要关闭它们。最好的做法是在顶层靠近资源finally
块Thread::run
。
Actually, you need to clean up your data, and not the thread.
实际上,您需要清理数据,而不是线程。