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(),而且只有在下一次垃圾收集过程中,
//才会真正回收对象的内存。
}
}
RunTime类的简单应用
最新推荐文章于 2022-12-09 17:55:52 发布