【发布时间】:2011-01-26 06:25:56
【问题描述】:
这个问题发布在某个网站上。我没有在那里找到正确的答案,所以我再次在这里发布。
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 运行时运行 GC,但线程并没有停止。
希望这次代码和问题都清楚。
【问题讨论】:
标签: java multithreading garbage-collection