这个问题在某个网站上发布过。我在那里没有找到正确的答案,所以我在这里再次发布它。
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,但线程就是不停止。
child.join()
时,它引用了child
。如果该引用(以及任何其他引用)未被丢弃,则无法对子线程进行垃圾回收。 - Blaisorblade