Java 线程终止参考
为什么不能通过将线程的引用设置为 null 并让垃圾收集器删除它来终止线程?它和其他物体一样,不是吗?
示例:
Thread t = new Thread(new Runnable() {
public void run() {
//...
}
}).start;
t = null;
Why is it not possible to terminate a thread by setting it's reference to null and letting the garbage collector removing it? It's an object like any other, isn't it?
example:
Thread t = new Thread(new Runnable() {
public void run() {
//...
}
}).start;
t = null;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,不是。它代表非内存资源。您是否期望一个文件被删除,因为代表它的对象被垃圾收集了?
事实上,当谈到垃圾回收时,
Thread
对象“与任何其他”对象“非常不同”,因为线程本身就是可达性树的根,因此,代表正在运行的线程的 Thread 对象的字段(或堆栈上的局部变量)引用的任何对象根据定义都不符合垃圾回收的条件。No, it's not. It represents a non-memory resource. Would you expect a file to be deleted because an object that represents it is garbage collected?
In fact, when it comes to garbage collection, a
Thread
object is very much not "like any other" object, because a thread is itself a root of the reachability tree, so any objects referred to by fields (or local variables on the stack) of a Thread object that represents a running thread are by definition not eligible for garbage collection.JLS 第 12.6 节这样说:
由此我们可以推断,活动线程是隐式可访问的,并且只要它们还活动,就不会被垃圾收集。尽管(正如 @Jon Skeet 所说)线程确实隐式地持有对其自身 Thread 对象的引用,但对 Thread 对象的可到达引用的存在与否并不相关,因此
Thread.currentThread()
会起作用。The JLS section 12.6 says this:
From this we can infer that live threads are implicitly reachable, and won't be garbage collected for as long as they are alive. The existence or otherwise of a reachable reference to the Thread object is not relevant, though (as @Jon Skeet says) a thread does implicitly hold a reference to its own Thread object, so that
Thread.currentThread()
will work.出于同样的原因,您不能仅将对 JFrame 的引用设置为 null 以使窗口神奇地消失。 JVM 有对线程的引用,因此即使您忘记了线程,JVM 也不会。您需要正确终止线程,最好是结束其主函数。
For the same reason you can't just set a reference to a JFrame to null to make the window magically disappear. The JVM has a reference to the thread, so even if you forget about the thread, the JVM won't. You'll need to terminate the thread properly, preferably by having its main function end.
您只是将变量的值设置为 null。
因此,问题是任何线程是否有效地拥有对该
Thread
对象的引用。考虑新线程本身...它可以很容易地包括如果 Thread 对象已被垃圾收集,您希望做什么?
对象仅在不再有对它们的实时引用之后的某个时刻被垃圾收集。任何活动线程都有对其自身的引用。
坦率地说,如果您必须确保您确实保留了刚刚启动的线程的引用,以防止它突然停止,那将是一件痛苦的事情。
You're only setting a variable's value to null.
So, the question is whether any thread effectively has a reference to that
Thread
object. Consider the new thread itself... it could easily includeWhat would you expect that to do if the
Thread
object had been garbage collected?Objects are only garbage collected at some point after there are no live references to them any more. Any live thread has a reference to itself.
Frankly, it would be a pain if you had to ensure that you did keep a reference a thread you've just started, in order to prevent it from being stopped abruptly.