if the reference of the thread is set to null.

来源:互联网 发布:印刷自动报价软件 编辑:程序博客网 时间:2024/05/25 16:37
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
    }
}
原创粉丝点击