我个人的想法,是不是直接写new Tank(..),这样他的引用已经丢失了,所以gc把这个垃圾清理了,而我上面的写法t2的引用仍然存在,所以不清理? 或者这样的情况要到内存快用完的时候才执行gc?

解决方案 »

  1.   

    t2是local variable,所以要等main函数退出后,才有可能被gc
      

  2.   

    System.gc();
    can't collect at once until the object have not reference
     
    you could try following:
    public class C4_13 {
    public static  void test()
    {
    new Tank(true);
    }
      public static void main(String[] args) { 
    test();
        Tank t1 = new Tank(false);
           t1.empty();
       
        System.gc();
      }
    }
      

  3.   

    class Tank {
      boolean isFull;
      
      public Tank(boolean isFull) {
        this.isFull = isFull;
      }
      public void fill() {
        System.out.println("Oil box is full !!");
        isFull = true;
      }
      public void empty() {
        System.out.println("Oil box is empty");
        isFull = false;
      }
      
      public void finalize() {
        if(isFull)
          System.out.println("An Error occurred, Oil box must be empty !!!");
      }
    }
    public class testeee {
    public static void test()
    {
    Tank t1 = new Tank(true);
    }
      public static void main(String[] args) {
       test();
        Tank t1 = new Tank(false);
        t1.fill();
         
       
        t1.empty();
        Tank t2 = new Tank(true); 
        t2.fill();
        System.gc();
      }
    }
      

  4.   

    gameboy999(-'_'-)说的我理解了,可能不深.
    但是我想,如果把t2设成静态变量呢?
    结果好像一样.
      

  5.   

    whbxm2000(咻咻), Ok, im going to try
      

  6.   

    要是你把t2设成静态变量,那只有当这个类从jvm中卸载的时候才可能被gc了~
    public class C4_13 {
      public static void main(String[] args) {
       
       {                   <---------------这里加个block就会发现t2,t1被gc了
        Tank t1 = new Tank(false);
        t1.fill();
        Tank t2 = new Tank(false);       <----- 这里
        t2.fill();
        t1.empty();
        }
        System.gc();
      }
    }
      

  7.   

    例子我明白了,还有个疑问,那就是gc会清理static变量吗? 因为书上说既使对象不存在了,static变量都存在,那么它们不是不会被gc了?
      

  8.   

    谢谢gameboy999(-'_'-) ,我发帖子的时候还没看到你的回答 :)
    现在我明白了