這個問題發佈在一些網站上。我沒有找到正確的答案,所以我在這裏再次發佈。Java線程垃圾收集與否
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,但線程不停止。
希望這次代碼和問題都很清楚。
這個答案,正如它目前的立場,引出了一個問題:線程是否可以被GC化(在它們終止之後)。由於此問題被標記爲[this one]的副本(http://stackoverflow.com/questions/10380327/java-threads-and-garbage-collector),因此應該提及線程將不再被標記爲「垃圾收集根「,因此它們可以被GC訪問。 – bluenote10 2014-08-30 09:09:18
@ bluenote10正確,因此短語「正在運行的線程」。 – falstro 2014-08-30 12:18:24
最後一句是滲透:「你的主線爲什麼不是垃圾......」。 – Determinant 2014-12-23 07:28:19