if the reference of the thread is set to null.
Q. After a thread started, if the reference of the thread is set to null,what will happen to the thread? Does it stop? Is it eligible for GC?
A: No.
Live thread will continue running even its reference is set to null. See JLS12.6.1
See an interesting example, run it, to see the results:
// TestThread.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();
t = null;
// 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: No.
Live thread will continue running even its reference is set to null. See JLS12.6.1
See an interesting example, run it, to see the results:
// TestThread.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();
t = null;
// 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
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.