Java运行时类



介绍

Java Runtime 类允许应用程序与应用程序运行的环境交互。

类声明

以下是java.lang.Runtime类的声明:

public class Runtime
   extends Object

类方法

序号 方法及描述
1 void addShutdownHook(Thread hook)

此方法注册一个新的虚拟机关闭钩子。

2 int availableProcessors()

此方法返回Java虚拟机可用的处理器数量。

3 Process exec(String command)

此方法在单独的进程中执行指定的字符串命令。

4 Process exec(String[] cmdarray)

此方法在单独的进程中执行指定的命令和参数。

5 Process exec(String[] cmdarray, String[] envp)

此方法在单独的进程中使用指定的环境执行指定的命令和参数。

6 Process exec(String[] cmdarray, String[] envp, File dir)

此方法在单独的进程中使用指定的环境和工作目录执行指定的命令和参数。

7 Process exec(String command, String[] envp)

此方法在单独的进程中使用指定的环境执行指定的字符串命令。

8 Process exec(String command, String[] envp, File dir)

此方法在单独的进程中使用指定的环境和工作目录执行指定的字符串命令。

9 void exit(int status)

此方法通过启动其关闭序列来终止当前正在运行的Java虚拟机。

10 long freeMemory()

此方法返回Java虚拟机中的可用内存量。

11 void gc()

此方法运行垃圾收集器。

12 static Runtime getRuntime()

此方法返回与当前Java应用程序关联的运行时对象。

13 void halt(int status)

此方法强制终止当前正在运行的Java虚拟机。

14 void load(String filename)

此方法将指定的filename加载为动态库。

15 void loadLibrary(String libname)

此方法加载具有指定库名称的动态库。

16 long maxMemory()

此方法返回Java虚拟机将尝试使用的最大内存量。

17 boolean removeShutdownHook(Thread hook)

此方法注销先前注册的虚拟机关闭钩子。

18 void runFinalization()

此方法运行任何挂起的最终化对象的最终化方法。

19 long totalMemory()

此方法返回Java虚拟机中的总内存量。

20 void traceInstructions(boolean on)

此方法启用/禁用指令跟踪。

21 void traceMethodCalls(boolean on)

此方法启用/禁用方法调用跟踪。

继承的方法

此类继承自以下类的方法:

  • java.lang.Object

示例:向线程对象添加关闭钩子

以下示例显示了Java Runtime addShutdownHook()方法的用法。在这个程序中,我们创建了一个静态内部类Message,它扩展了Thread。在main方法中,我们使用addShutdownHook()方法用一个新的Message对象注册了一个关闭钩子。然后我们将系统休眠2秒,然后打印一条关闭消息。由于关闭钩子已注册到Message对象,因此当程序退出时,将调用其run方法。

package com.tutorialspoint;

public class RuntimeDemo {

   // a class that extends thread that is to be called when program is exiting
   static class Message extends Thread {

      public void run() {
         System.out.println("Bye.");
      }
   }

   public static void main(String[] args) {
      try {

         // register Message as shutdown hook
         Runtime.getRuntime().addShutdownHook(new Message());

         // print the state of the program
         System.out.println("Program is starting...");

         // cause thread to sleep for 3 seconds
         System.out.println("Waiting for 3 seconds...");
         Thread.sleep(3000);

         // print that the program is closing 
         System.out.println("Program is closing...");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

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

Program is starting...
Waiting for 3 seconds...
Program is closing...
Bye.
广告
© . All rights reserved.