Java Thread Garbage collected or not(Java 线程垃圾是否收集)
问题描述
这个问题发布在某个网站上.我没有在那里找到正确的答案,所以我再次在这里发布.
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 线程垃圾是否收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 线程垃圾是否收集
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01