📜  Java Java类

📅  最后修改于: 2022-05-13 01:55:32.331000             🧑  作者: Mango

Java Java类

在Java中, Runtime 类用于与每个具有 Runtime 类的单个实例的Java应用程序交互,该实例允许应用程序与应用程序运行的环境进行交互。当前运行时可以通过 getRuntime() 方法获得。

Java Runtime 类的方法

Method Action Performed
addShutdownHook(Thread hook)Registers a new virtual-machine shutdown hook thread.
availableProcessors()Returns the number of processors available to the JVM (Java virtual machine)
exec(String command)Executes the given command in a separate process
exec(String[] cmd)Executes the specified command and arguments in a separate process.
exec(String command, String[] envp, File dir)Executes the specified string command in a separate process with the specified environment and working directory. 
exec(String command, String[] envp)Executes the specified string command in a separate process with the specified environment.
exec(String[] cmdarray, String[] envp, File dir) Executes the specified command and arguments in a separate process with the specified environment and working directory.
exec(String[] cmdarray, String[] envp)Executes the specified command and arguments in a separate process with the specified environment. 
exit(int status)Terminates the currently running Java virtual machine by initiating its shutdown sequence.
freeMemory()Returns the amount of free memory in the JVM(Java Virtual Machine)
gc()Runs the garbage collector. Calling this method suggests that the Java virtual machine expands effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.
getRuntime()Returns the instance or Runtime object associated with the current Java application
halt(int status)Forcibly terminates the currently running Java virtual machine. This method never returns normally. This method should be used with extreme caution.
load(String filename)Loads the specified filename as a dynamic library. The filename argument must be a complete pathname.
loadLibrary(String libname)Loads the dynamic library with the specified library name. A file containing code is loaded from the local system from a place where library files are conventionally obtained.
maxMemory()Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned
removeShutdownHook(Thread hook)De-registers a previously-registered virtual machine shutdown hook.
runFinalization()Runs the finalization methods of any objects pending finalization. It suggests that JVM (Java virtual machine) expands effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run.
totalMemory()Returns the amount of total memory in the JVM(Java Virtual Machine) 
traceInstructions(boolean a)Enables or disables tracing of instructions. If the boolean argument is true then it will suggest that the JVM emits debugging information for each instruction in the virtual machine as it is executed.
traceMethodCalls(boolean a)Enables or disables tracing of method calls. If the boolean argument is true then it will suggest that the Java virtual machine emits debugging information for each method in the virtual machine as it is called.

示例 1:

Java
// Java Program to Illustrate Runtime class
// Via getRuntime(), freeMemory() and
// totalMemory() Method
 
// Importing required classes
import java.lang.*;
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Method 1: getRuntime()
        // Getting the current runtime associated
        // with this process
        Runtime run = Runtime.getRuntime();
 
        // Printing the current free memory for this runtime
        // using freeMemory() method
        System.out.println("" + run.freeMemory());
 
        // Method 2: freeMemory()
        // Printing the number of free bytes
        System.out.println(
            "" + Runtime.getRuntime().freeMemory());
 
        // Method 3: totalMemory()
        // Printing the number of total bytes
        System.out.println(
            "" + Runtime.getRuntime().totalMemory());
    }
}


Java
// Java Program to Illustrate Runtime class
// Via exec() Method
 
// Importing required classes
import java.util.*;
import java.lang.*;
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to chcek for exceptions
        try {
           
            // Creating a process and execute google-chrome
            Process process = Runtime.getRuntime().exec(
                "google-chrome");
            System.out.println(
                "Google Chrome successfully started");
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
            // Display the exception on the console
            e.printStackTrace();
        }
    }
}


Java
// Java Program to Illustrate Runtime class
// Via availableProcessors() Method, exit() Method
 
// Importing required classes
import java.util.*;
import java.lang.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Method 1: availableProcessors()
        // Check the number of processors available
        // and printing alongside
        System.out.println("" + Runtime.getRuntime()
                           .availableProcessors());
 
 
        // Method 2: exit()
        // Making program to exit
        Runtime.getRuntime().exit(0);
 
        // Nothing will run now
        System.out.println("Program Running Check");
 
        // Note: here we will notice that there will be no
        // output generated on console
 
    }
}


Java
// Java Program to illustrate Runtime Class
// Via loadLibrary(), runFinalization()
// gc(), maxMemory()
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Method 1: loadLibrary()
        // Loading a library that is home/saket/Desktop
        // folder
        Runtime.getRuntime().loadLibrary(
            "/home/saket/Desktop/Library");
 
        System.out.println("Library Loaded Successfully");
 
        // Method 2: runFinalization()
        // Run the finalization
        Runtime.getRuntime().runFinalization();
 
        // Print statement
        System.out.println("Finalized");
 
        // Method 3: gc()
        // Run the garbage collector
        Runtime.getRuntime().gc();
 
        System.out.println("Running");
 
        // Method 4: maxMemory()
 
        // Printing  the maximum memory
        System.out.println(
            "" + Runtime.getRuntime().maxMemory());
    }
}


Java
// Java program to illustrate halt()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        // halt this process
        Runtime.getRuntime().halt(0);
 
        // print a string, just to see if it process is halted
        System.out.println("Process is still running.");
    }
}


Java
// Java Program to Illustrate exec()
// Method of Runtime class
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Try block to check for exceptions
        try {
 
            // Declaring a string array
            String[] cmd = new String[2];
 
            // Initializing elements of string array
            cmd[0] = "atom";
            cmd[1] = "File.java";
 
            // Creating a file with directory from local systems
            File dir = new File("/Users/mayanksolanki/Desktop");
 
            // Creating a process by creating Process class object
            // and execute above array using exec() method
            Process process = Runtime.getRuntime().exec(cmd, null);
 
            // Display message on console for successful execution
            System.out.println("File.java opening.");
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Display exceptions with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
}


输出
132579840
132285936
134217728

示例 2:

Java

// Java Program to Illustrate Runtime class
// Via exec() Method
 
// Importing required classes
import java.util.*;
import java.lang.*;
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to chcek for exceptions
        try {
           
            // Creating a process and execute google-chrome
            Process process = Runtime.getRuntime().exec(
                "google-chrome");
            System.out.println(
                "Google Chrome successfully started");
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
            // Display the exception on the console
            e.printStackTrace();
        }
    }
}

输出:

Google Chrome successfully started

示例 3:

Java

// Java Program to Illustrate Runtime class
// Via availableProcessors() Method, exit() Method
 
// Importing required classes
import java.util.*;
import java.lang.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Method 1: availableProcessors()
        // Check the number of processors available
        // and printing alongside
        System.out.println("" + Runtime.getRuntime()
                           .availableProcessors());
 
 
        // Method 2: exit()
        // Making program to exit
        Runtime.getRuntime().exit(0);
 
        // Nothing will run now
        System.out.println("Program Running Check");
 
        // Note: here we will notice that there will be no
        // output generated on console
 
    }
}
输出
4

从上面的输出可以清楚地看出,exit() 方法不会让下面的打印语句执行,因为控制台上没有打印“程序运行检查”。如果我们注释掉availableProcessors()的工作,可以清楚地看出exit()方法输出如下:

示例 4:

Java

// Java Program to illustrate Runtime Class
// Via loadLibrary(), runFinalization()
// gc(), maxMemory()
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Method 1: loadLibrary()
        // Loading a library that is home/saket/Desktop
        // folder
        Runtime.getRuntime().loadLibrary(
            "/home/saket/Desktop/Library");
 
        System.out.println("Library Loaded Successfully");
 
        // Method 2: runFinalization()
        // Run the finalization
        Runtime.getRuntime().runFinalization();
 
        // Print statement
        System.out.println("Finalized");
 
        // Method 3: gc()
        // Run the garbage collector
        Runtime.getRuntime().gc();
 
        System.out.println("Running");
 
        // Method 4: maxMemory()
 
        // Printing  the maximum memory
        System.out.println(
            "" + Runtime.getRuntime().maxMemory());
    }
}

输出:

Library Loaded Successfully
Finalized
Running
2147483648

示例 5:

Java

// Java program to illustrate halt()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        // halt this process
        Runtime.getRuntime().halt(0);
 
        // print a string, just to see if it process is halted
        System.out.println("Process is still running.");
    }
}

输出:

从上面的输出可以看出上面的程序编译成功并运行。没有执行打印语句,因为我们使用了停止进一步执行操作的 halt() 方法。

示例 6:

Java

// Java Program to Illustrate exec()
// Method of Runtime class
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Try block to check for exceptions
        try {
 
            // Declaring a string array
            String[] cmd = new String[2];
 
            // Initializing elements of string array
            cmd[0] = "atom";
            cmd[1] = "File.java";
 
            // Creating a file with directory from local systems
            File dir = new File("/Users/mayanksolanki/Desktop");
 
            // Creating a process by creating Process class object
            // and execute above array using exec() method
            Process process = Runtime.getRuntime().exec(cmd, null);
 
            // Display message on console for successful execution
            System.out.println("File.java opening.");
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Display exceptions with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
}

输出:

File.java opening.