问题
单一线程中,当程序执行System.gc()
后,立即让该线程休眠,是否一定会触发一次gc操作。
代码测试
public class Test {
String msg = "nihao";
public static void main(String[] args) {
Test test = new Test();
System.out.println("first"+test.msg);
test = null;
System.gc();
try {
System.out.println("secend");
Thread.sleep(1000);
System.out.println("four");
} catch (Exception e) {
e.printStackTrace();
}
}
protected void finalize(){
System.out.println("third");
}
}
运行结果
C:\Users\C5-0\tmp>java Test
firstnihao
secend
third
four
C:\Users\C5-0\tmp>java Test
firstnihao
secend
third
four
C:\Users\C5-0\tmp>java Test
firstnihao
secend
third
four
C:\Users\C5-0\tmp>java Test
firstnihao
secend
third
four
结论
通过上述的测试结果,我们猜测触发线程的休眠会触发一次gc操作。但是在java中,gc操作执行的时间只是由JVM来控制的,即使程序中有System.gc()
,也只是告诉JVM:我需要你执行一次gc操作,但是具体的操作时间任然由JVM决定,可能程序结束都不会执行,也可能马上执行,所以,会触发上述的结果可能只是一个巧合,记住一点即可:Java中,gc操作的时间是由JVM(java虚拟机)决定的!