概述
如果将线程启动后,然后线程变量置空,线程会怎么样?
importjava.lang.ref.WeakReference; public class TestThread { public static void testUnreferencedThread() { // 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(); WeakReference<Thread> wr = new WeakReference<Thread>(t); t = null; // no more references for Thread t // another infinite loop while (true) { try { Thread.sleep(3000); } catch (InterruptedException e) { } System.gc(); StringBuilder sb = new StringBuilder(); sb.append("Executed System.gc(),"); if(wr.get()==null) { sb.append(" thread variable has been GCed"); } else { sb.append("WeakReference still keep ").append(wr.get()); } System.out.println(sb.toString()); } // The program will run forever until you use ^C to stop it } public static void main(String[] s) { testUnreferencedThread(); } }
上面的例程运行结果是两个线程在程序被强制终止之前一直运行。
threadis running... thread is running... thread is running... Executed System.gc(),WeakReference still keep Thread[Thread-0,5,main] thread is running... thread is running... thread is running... Executed System.gc(),WeakReference still keep Thread[Thread-0,5,main] thread is running... thread is running... ... ... ...
运行中的线程是称之为垃圾回收根对象的一种,不会被垃圾回收。当垃圾回收器判断一个对象是否可达,总是使用垃圾回收根对象作为参考点。
例如,主线程并没有被引用,但是不会被垃圾回收。
垃圾回收根对象是可在堆之外被访问的对象。一个对象可由于下列原因成为GC根对象:
- System
Class
- JNI
Local
- JNI
Global
- Thread
Block
- Thread
- Busy
Monitor
- Java
Local
- Native
Stack
- Finalizer
- Unfinalized
- Unreachable
从其他根对象不可达的对象,但是被内存分析器标记为根对象。
- Unknown
参考
http://stackoverflow.com/questions/2423284/java-thread-garbage-collected-or-not
http://help.eclipse.org/indigo/topic/org.eclipse.mat.ui.help/concepts/gcroots.html
转载自:http://blog.sina.com.cn/s/blog_72ef7bea0101cthq.html
最后
以上就是细腻路灯为你收集整理的Java线程是否会被垃圾回收的全部内容,希望文章能够帮你解决Java线程是否会被垃圾回收所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复