Java 系统 gc() 方法



描述

Java System gc() 方法运行垃圾回收器。调用此方法表示建议 Java 虚拟机努力回收未使用的对象,以便使它们当前占用的内存可供快速重用。

声明

以下是 java.lang.System.gc() 方法的声明

public static void gc()

参数

返回值

此方法不返回值。

异常

示例:运行垃圾回收器

以下示例显示了 Java System gc() 方法的使用。在此程序中,我们创建了两个数组并对其进行了初始化。使用 arraycopy() 方法,将第一个数组的第一个元素复制到第二个数组,并打印数组 2。现在,使用 System.gc(),我们指示 JVM 运行垃圾回收器以清理内存。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {

      int arr1[] = { 0, 1, 2, 3, 4, 5 };
      int arr2[] = { 0, 10, 20, 30, 40, 50 };
    
      // copies an array from the specified source array
      System.arraycopy(arr1, 0, arr2, 0, 1);
      System.out.print("array2 = ");
      for(int i= 0; i < arr2.length; i++) {
    	  System.out.print(arr2[i] + " ");
      }
      
      // it runs the GarbageCollector
      System.gc();
      System.out.println("Cleanup completed..."); 
   }
} 

输出

让我们编译并运行以上程序,这将产生以下结果:

array2 = 0 10 20 30 40 50
Cleanup completed...
java_lang_system.htm
广告

© . All rights reserved.