使用NEW 实现一个垃圾回收机制的测试小程序
不停的打印输出一句话.

解决方案 »

  1.   

    楼主试试这个:import java.util.Arrays;
    public class CsdnGarbageCollect
    {
    static int number=0;
    int objectId=number++; //对象的序号,自动加1。
    int[] intArray=new int[10000]; //定义一个比较占内存的数组。可调整。
    public CsdnGarbageCollect()
    {
    Arrays.fill(intArray,999999); //初始化。
    System.out.println("Now the number"+objectId+" object is being created!");
    } public void finalize() //覆写 Object 的finalize() 方法。
    {
    System.out.println("Now the number "+objectId+" object is a garbage and will going!");
    } public static void main(String[] args)
    {
    int i=0;
    while(i<200) //循环次数可调。
    {
    i++; //计数。
    new CsdnGarbageCollect(); //产生对象。
    try //程序休眠一会。时间可调。
    {
    Thread.sleep(10); //时间也可调。
    }
    catch(InterruptedException ie)
    {
    ie.printStackTrace();
    }
    System.gc(); //通知jvm回收垃圾。注释掉和加上看效果。
    }
    }
    }