搜索

首页  >  问答  >  正文

java - 关于System.gc()的执行?

package FinalizeTest;

public class Person {
    
    public Person(){
        System.out.println("person created");
    }

    @Override
    protected void finalize() throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("gc ");
        throw new Exception("no effect");
    }
}



package FinalizeTest;

public class MainTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Person per = new Person();
        per = null;
        System.gc();
        System.out.println("hello world");

    }

}

输出为

person created
hello world
gc 

代码如上所示, 求解释为什么hello world会在gc之前输出??

PHP中文网PHP中文网2889 天前277

全部回复(4)我来回复

  • PHP中文网

    PHP中文网2017-04-17 17:59:13

    关于java的 finalize() 不要与c/c++混淆了,java程序员从来不能决定垃圾回收的时机。
    官方描述:finalize() 不要与c/c++混淆了,java程序员从来不能决定垃圾回收的时机。
    官方描述:

    Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

    finalize()

    Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

    finalize()只是定义了回收时的动作,但具体何时回收仍旧由垃圾回收器自己决定。🎜 🎜仔细看下javadoc🎜

    回复
    0
  • 迷茫

    迷茫2017-04-17 17:59:13

    System.gc(); 只是告诉gc进行一次回收动作,但是回收什么还是由gc自己决定的

    回复
    0
  • 黄舟

    黄舟2017-04-17 17:59:13

    System.gc() 的作用只是提醒虚拟机进行垃圾回收,回不回收得由虚拟机决定。

    你可以理解为这个动作是异步的。

    回复
    0
  • ringa_lee

    ringa_lee2017-04-17 17:59:13

    说的简单点就是,虽然你主动调用了System.gc();但是它回不回收和什么时候回收都由垃圾回收器自己来做,它和你没有直接关系,你执行你的代码,它执行它的垃圾回收。

    回复
    0
  • 取消回复