Java Basics--Runtime class (encapsulating virtual machine)

introduce

The Runtime class is used to represent the running state of the virtual machine, and it is used to encapsulate the JVM virtual machine process. Every time you use the java command to start the virtual machine, there is one Runtime instance, and there is only one instance.

Therefore, when the Runtime class is defined, its construction method has been privatized (the application of the singleton design pattern), and the object cannot be instantiated directly. If you want to obtain a Runtime instance in the program, you can only use the following methods:

Runtime runtime = Runtime.getRuntime();

Because the Runtime class encapsulates the virtual machine process, in the program, the instance object of this class is usually used to obtain the relevant information of the current virtual machine.

Common methods and functions include:

  1. getRuntime(): This static method returns the runtime object of the current Java application.
  2. exec(String command): This method is used to execute the specified command in the operating system. It creates a new process and executes the given command in it.
  3. freeMemory(): Returns the amount of free memory in the current Java virtual machine.
  4. maxMemory(): Returns the maximum amount of memory that the Java virtual machine can use, that is, the maximum capacity of the heap.
  5. availableProcessors(): Returns the number of available processors.
  6. totalMemory(): Returns the total amount of memory currently used by the Java virtual machine.

These methods allow a Java application to interact with its runtime environment, obtain memory usage, execute system commands, and more. It should be noted that when using exec()methods to execute system commands, it may be necessary to handle input and output streams in order to communicate with subprocesses and properly handle possible exceptions .

Get current virtual machine information

The Runtime class can obtain information about the number of processors, the amount of free memory, the maximum amount of available memory, and the total amount of memory of the current Java virtual machine.

public class myclass {
	public static void main(String[] args) {
		Runtime rt = Runtime.getRuntime(); // 获取
		System.out.println("处理器的个数: " + rt.availableProcessors()+"个");
		System.out.println("空闲内存数量: " + rt.freeMemory() / 1024 / 1024 
        + "M");
		System.out.println("最大可用内存数量: " + rt.maxMemory() / 1024 / 
        1024 + "M");
        System.out.println("虚拟机中内存总量: " + rt.totalMemory() / 1024 / 
         1024 + "M");
	}
 }

Due to the different machine configurations of each person, the print results of this example may be different. In addition, the number of free memory, the maximum number of available memory, and the total amount of memory are all calculated in bytes. The above running results have been converted from bytes to megabytes. (M).  

operating system process

The Runtime class provides an exec() method, which is used to execute a dos command, so as to achieve the same effect as entering the dos command in the command line window. For example, open a Notepad program that comes with Windows by running the "notepad.exe" command.

import java.io.IOException;
 public class myclass{
	public static void main(String[] args) throws IOException {
		Runtime rt = Runtime.getRuntime(); // 创建Runtime实例对象
		rt.exec("notepad.exe"); // 调用exec()方法
	}
 }

After the program runs, a new process notepad.exe will be generated in the Windows system, which can be observed through the task manager. 

Check the API documentation and you will find that the exec() method of the Runtime class returns a Process object, which is the new process generated by exec(), through which the new process can be managed. To close this process, just call destroy () method is enough. Having code look like this:

import java.io.IOException;

public class MyClass {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("notepad.exe");

            // 休眠3秒
            Thread.sleep(3000);

            // 关闭记事本应用程序
            Runtime.getRuntime().exec("taskkill /F /IM notepad.exe");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In the above code, the open Notepad is closed by calling the destroy() method of the Process object. In order to highlight the effect of the demonstration, the static method sleep(long millis) of the Thread class is used to make the program sleep for 3 seconds. Therefore, after the program runs, you will see that the opened Notepad will automatically close after 3 seconds. 

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/132269501