当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Runtime getRuntime()用法及代码示例


在 Java 中,Runtime 类允许您与应用程序的运行时环境进行交互。该类提供的基本方法之一是getRuntime()。此方法返回与当前 Java 应用程序关联的运行时对象。通过此对象,您可以访问有关运行时环境的信息、执行系统命令、管理进程等。

Java 运行时 getRuntime() 方法

Runtime.getRuntime() 方法是一个静态方法,用于检索当前 Java 应用程序的运行时对象。该对象允许您访问应用程序运行时环境的各个方面,例如执行系统命令、管理进程和查询内存使用情况。

用法:

public static Runtime getRuntime()

Java 运行时示例getRuntime()

现在,让我们探讨一些使用运行时对象的实际示例:

Java


// Java Program to implement 
// Java Runtime getRuntime() 
import java.io.IOException; 
  
// Driver Class 
public class GfgRuntimeExample { 
    // main function 
    public static void main(String[] args) 
    { 
        // Getting the runtime object 
        Runtime runtime = Runtime.getRuntime(); 
  
        // Example 1: Executing System Command 
        try { 
            // Executing a system command to open a web page 
            // (https://www.gfg.com) 
            Process process = runtime.exec( 
                "xdg-open https://www.gfg.com"); 
  
            // Waiting for the process to complete and 
            // retrieving the exit code 
            int exitCode = process.waitFor(); 
  
            // Printing the exit code 
            System.out.println( 
                "Example 1: Executing System Command"); 
            System.out.println("Exit Code: " + exitCode); 
        } 
        catch (IOException | InterruptedException e) { 
            e.printStackTrace(); 
        } 
  
        // Example 2: Retrieving Available Processors 
        int processors = runtime.availableProcessors(); 
        System.out.println( 
            "\nExample 2: Retrieving Available Processors"); 
        System.out.println("Available Processors: "
                           + processors); 
  
        // Example 3: Querying Total and Free Memory 
        long totalMemory = runtime.totalMemory(); 
        long freeMemory = runtime.freeMemory(); 
  
        // Converting memory values to megabytes (MB) 
        long totalMemoryMB = totalMemory / (1024 * 1024); 
        long freeMemoryMB = freeMemory / (1024 * 1024); 
  
        System.out.println( 
            "\nExample 3: Querying Total and Free Memory"); 
        System.out.println("Total Memory (MB): "
                           + totalMemoryMB); 
        System.out.println("Free Memory (MB): "
                           + freeMemoryMB); 
    } 
}

输出:

Example 1: Executing System Command
Exit Code: 0
Example 2: Retrieving Available Processors
Available Processors: 4
Example 3: Querying Total and Free Memory
Total Memory (MB): 123
Free Memory (MB): 78

结论

Runtime.getRuntime() 方法提供对 Java 应用程序的运行时环境的访问。您可以使用它来执行系统命令、管理进程以及检索有关系统资源(例如可用处理器和内存使用情况)的信息。



相关用法


注:本文由纯净天空筛选整理自bishaldubey大神的英文原创作品 Java Runtime getRuntime() Method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。