当前位置:  首页>> 技术小册>> Java语言基础9-常用API和常见算法

3.2.1 概述

  • 每个应用程序都有一个 Runtime 类的实例,使得应用程序能够和其运行的环境相连接。
  • 应用程序不能创建自己的 Runtime 实例,只能通过 getRuntime() 方法获取当前的运行时。

3.2.2 常用方法

  • 返回与当前 Java 应用程序相关的运行时对象:
  1. public static Runtime getRuntime() {}

返回 Java 虚拟机中的内存总量(此方法返回的值可能随时间的推移而变化,这取决于主机环境):

  1. public native long totalMemory();

返回 Java 虚拟机中的空闲内存量(调用 gc 方法可能导致 freeMemory 返回值的增加):

  1. public native long freeMemory();

示例:

  1. package com.github.runtime.demo;
  2. /**
  3. * @author maxiaoke.com
  4. * @version 1.0
  5. */
  6. public class Test {
  7. public static void main(String[] args) {
  8. Runtime runtime = Runtime.getRuntime();
  9. Runtime runtime1 = Runtime.getRuntime();
  10. System.out.println(runtime == runtime1); // true
  11. long totalMemory = runtime.totalMemory();
  12. System.out.println("totalMemory = " + totalMemory); // 512753664
  13. long freeMemory = runtime.freeMemory();
  14. System.out.println("freeMemory = " + freeMemory); // 504700544
  15. }
  16. }

该分类下的相关小册推荐: