问题描述
这个问题发布在某个网站上.我没有在那里找到正确的答案,所以我再次在这里发布.
This question was posted on some site. I didnt find right answers there, so I am posting it here again.
public class TestThread {
public static void main(String[] s) {
// anonymous class extends Thread
Thread t = new Thread() {
public void run() {
// infinite loop
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// as long as this line printed out, you know it is alive.
System.out.println("thread is running...");
}
}
};
t.start(); // Line A
t = null; // Line B
// no more references for Thread t
// another infinite loop
while (true) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
System.gc();
System.out.println("Executed System.gc()");
} // The program will run forever until you use ^C to stop it
}
}
我的查询不是关于停止线程.让我重新表述我的问题.A行(见上面的代码)启动一个新线程;和 B 行使线程引用为空.因此,JVM 现在有一个不存在引用的线程对象(处于运行状态)(如 B 行中的 t=null).所以我的问题是,为什么这个线程(在主线程中不再有引用)一直运行直到主线程运行.根据我的理解,线程对象应该在 B 行后被垃圾回收.我尝试运行此代码 5 分钟或更长时间,请求 Java Runtime 运行 GC,但线程并没有停止.
My query is not about stopping a Thread. Let me rephrase my question. Line A(see code above) starts a new Thread; and Line B make the thread reference null. So, the JVM now has a Thread Object(which is in running state) to which no reference exists (as t=null in Line B). So my question is, why does this thread(that has no reference anymore in the main thread) keeps on running until the main thread is running. Per my understanding, the thread object should have been garbage collected post Line B. I tried to run this code for 5 minutes and more, requesting Java Runtime to run GC, but the thread just does not stop.
希望这次代码和问题都清楚.
Hope both the code and question is clear this time.
推荐答案
正在运行的线程被认为是所谓的垃圾收集根,是防止垃圾收集的东西之一.当垃圾收集器确定您的对象是否为 'reachable' 与否,它总是使用垃圾收集器根集作为参考点.
A running thread is considered a so called garbage collection root and is one of those things keeping stuff from being garbage collected. When the garbage collector determines whether your object is 'reachable' or not, it is always doing so using the set of garbage collector roots as reference points.
考虑一下,为什么你的主线程没有被垃圾收集,也没有人引用那个.
Consider this, why is your main thread not being garbage collected, no one is referencing that one either.
这篇关于Java 线程垃圾是否收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!