RunTime类的简单应用

class Person
    {
        private  String name;
        private int age;
        public Person(String name,int age){
            this.name=name;
            this.age=age;
        }    
        public void finalize() throws Throwable {
            
            System.out.println("我被回收了,完蛋了....("+this+")");     //"+this+"调用toString()方法
        }
        public String toString(){
            
            return "姓名"+this.name+" 年龄 "+this.age;
        }        
    }
public class Demo_RunTime
{       
  public static void main(String args[])throws Exception
    { 
      Runtime run = Runtime.getRuntime();   
     // Process p = run.exec("notepad"); 
      System.out.println("1.最大内存空间:"+run.maxMemory());
      System.out.println("1.空闲内存空间:"+run.freeMemory());
      System.out.println("1.总共内存空间:"+run.totalMemory());
      
      System.out.println("以下产生大量垃圾");
      String str=null;
          for(int i=0;i<3000;i++){
              str+=i;   //会产生大量垃圾
          }   
            System.out.println("2.最大内存空间:"+run.maxMemory());
          System.out.println("2.空闲内存空间:"+run.freeMemory());
          System.out.println("2.总共内存空间:"+run.totalMemory());
          System.out.println( "产生大量垃圾后还有  "+run.freeMemory()+" 内存空间");
          run.gc();//垃圾回收
          System.out.println("     垃圾回收后:         "+run.freeMemory());
          //system类
          long begin=System.currentTimeMillis();
          String str1=null;
          for(int i=0;i<3000;i++){
              str1+=i;   //会产生大量垃圾
          }
          long end=System.currentTimeMillis();
          System.out.println(end-begin);  //计算用时
          
          //System与垃圾回收  调用gc()方法就相当于调用Runtime类中的gc()方法
          
          
          Person person=new Person("马建杰",22);
          person=null;  //取消引用  后会调用finalize()
          
          System.gc();  //强制进行垃圾收集
          
          //Java提供了一个名为finalize()的方法,它的工作原理应该是这样的:一旦垃圾收集器准
          //备好释放对象占用的存储空间,它首先调用finalize(),而且只有在下一次垃圾收集过程中,
          //才会真正回收对象的内存。
          
    }   
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值