Runtime class in java example

Русские Блоги

Класс Runtime инкапсулирует среду выполнения. Каждое Java-приложение имеет экземпляр класса Runtime, позволяющий приложению подключаться к среде, в которой оно выполняется.

Мы не можем создать экземпляр объекта Runtime, а приложение не может создать собственный экземпляр класса Runtime, но мы можем получить ссылку на текущий объект Runtime через метод getRuntime. Как только вы получите ссылку на текущий объект Runtime, вы можете вызвать метод объекта Runtime дляУправление состоянием и поведением виртуальной машины Java

Когда апплеты и другой ненадежный код вызывают какие-либо методы времени выполнения, это часто вызывает исключение SecurityException.

Пример метода API

Давайте посмотрим на несколько нативных методов:

public native int availableProcessors(); public native long freeMemory(); public native long totalMemory(); public native long maxMemory();

Примеры использования следующие:

Runtime rt = Runtime.getRuntime(); System.out.println ("Количество процессоров:" + rt.availableProcessors ()); // Количество процессоров: 4 System.out.println ("Количество свободной памяти:" + rt.freeMemory () / 1024/1024 + "МБ"); // Количество свободной памяти: 111 МБ System.out.println ("Общий объем памяти:" + rt.totalMemory () / 1024/1024 + "МБ"); // Общий объем памяти: 120 МБ System.out.println ("Максимально доступная память:" + rt.maxMemory () / 1024/1024 + "mb"); // Максимально доступная память: 1910 МБ

Используйте сценарий:
С помощью методов totalMemory () и freeMemory () вы можете узнатьКуча памятиНасколько он велик и сколько осталось.

Java периодически перерабатывает мусорные объекты (неиспользуемые объекты), чтобы освободить пространство памяти. Но если вы хотите собрать отброшенные объекты до следующего указанного цикла сборщика, вы можете запустить сборщик мусора по мере необходимости, вызвав метод gc (). Хороший метод тестирования — вызвать метод gc (), затем вызвать метод freeMemory (), чтобы проверить основное использование памяти, затем выполнить код и затем снова вызвать метод freeMemory (), чтобы увидеть, сколько памяти выделено.

  • метод version () (начиная с Java9)
    java9t предоставляет метод Version, который может помочь нам легко получить информацию о параметрах во время выполнения, что можно назвать очень удобным для пользователя. Мы смотрим на исходный код этого метода:
public static Version version() < if (version == null) < version = new Version(VersionProps.versionNumbers(), VersionProps.pre(), VersionProps.build(), VersionProps.optional()); >return version; >

Мы обнаружили, что все параметры взяты из VersionProps, поэтому мы разместили часть его исходного кода, всем будет понятно

class VersionProps < private static final String launcher_name = "java"; private static final String java_version = "10.0.2"; private static final String java_version_date = "2018-07-17"; private static final String java_runtime_name = "Java(TM) SE Runtime Environment"; private static final String java_runtime_version = "10.0.2+13"; private static final String VERSION_NUMBER = "10.0.2"; private static final String VERSION_BUILD = "13"; private static final String VERSION_PRE = ""; private static final String VERSION_OPT = ""; private static final boolean isLTS = "".startsWith("LTS"); private static final String VENDOR_VERSION_STRING = "18.3"; private static final String vendor_version = (VENDOR_VERSION_STRING.length() >0 ? " " + VENDOR_VERSION_STRING : ""); static < init(); >>

Поскольку моя версия JDK — Java10, ваши параметры могут не совпадать с моими. Я запускаю это следующим образом:

System.out.println(Runtime.version()); //10.0.2+13

Выполните другие процедуры

В безопасной среде это может быть в многозадачной операционной системеИспользуйте Java для выполнения других особенно крупных процессов(То есть программа). Метод ecec () имеет несколько форм для именования программы, которую вы хотите запустить, и ее входных параметров. Метод ecec () возвращает объект Process, который можно использовать для управления взаимодействием между программой Java и вновь запущенным процессом. Метод ecec () существенно зависит от среды.

 public static void main(String[] args) throws IOException < Runtime rt = Runtime.getRuntime(); //rt.exec("notepad.exe "); // Открыть блокнот Замечания: .exe можно не указывать Process process = rt.exec ("calc.exe"); // Открыть калькулятор System.out.println(process); //Process[pid=8108, exitValue="not exited"] >

После запуска новой программы вы можете использовать метод Process. Вы можете использовать метод destroy (), чтобы убить дочерний процесс,Вы также можете использовать метод waitFor (), чтобы дождаться окончания программы., Метод exitValue () возвращает значение, возвращаемое в конце дочернего процесса. Если ошибки нет, она вернет 0, иначе вернет ненулевое значение.

public static void main(String[] args) throws IOException, InterruptedException < Runtime rt = Runtime.getRuntime(); Process process = rt.exec ("notepad.exe"); // Открыть блокнот. Примечание. .Exe можно не указывать // Process process = rt.exec ("calc.exe"); // Открыть калькулятор process.waitFor (); // Блокировать до завершения выполнения дочернего процесса System.out.println («Выполнение слова выполнено ~~~»); process.destroyForcbly (); // Принудительно уничтожить дочерний процесс destroy >Результат операции: (Когда вы закрываете Блокнот, он запускает программу и печатает информацию)

Методы, связанные с Gc

  • exit(int status)
    • При запуске последовательности выключения виртуальной машины работающая в данный момент виртуальная машина Java завершается.
    • Запустите сборщик мусора.
    • Принудительное завершение работающей в данный момент виртуальной машины Java.

    загрузить и загрузить библиотеку

    Эти два метода являются очень важной функцией, которую мы будем использовать при использовании механизма JNI в Java, функция которого заключается в загрузке библиотеки, которая реализует собственный метод, который мы объявили в коде Java, или загрузке других Библиотека динамических ссылок

    Программирование JNI используется здесь. Младший брат не хорошо, здесь можно дать только сокращенную заглавную букву

    Источник

    Java Runtime class

    Java Runtime class

    The class used for the interaction with the run time environment of Java is called run time class in Java which provides several methods such as Runtime.getRuntime(), exit(int status), addShutdownHook(Thread hook), Process exec(String command) throws an input-output exception, availableProcessors(), freeMemory(), totalMemory(), etc. for process execution, for invoking GC, to obtain the total memory, to obtain the free memory, etc. whose declaration is public class Runtime extends object and only one application of Java can use only one instance of java.lang.Runtime class and a singleton instance of Runtime class is returned using Runtime.getRuntime() method in Java.

    Web development, programming languages, Software testing & others

    Methods of Java Runtime class

    There are several methods of Java Runtime Class. They are:

    1. Runtime getRuntime()

    An instance of the Run time class is returned using the Runtime getRuntime() method. Consider the below Java program to demonstrate the Runtime getRuntime() method of the Java Run time class.

    //a class called program is defined public class program < //main method is called public static void main(String[] args) < // The current runtime in association with process is obtained using getRuntime method. Runtime roll = Runtime.getRuntime(); // The current free memory for the current runtime is obtained using freeMemory() method. System.out.println("The current free memory for the current runtime is" + roll.freeMemory()); >>

    Java Runtime Class Example 1

    Explanation: In the above program, a class called program is defined. Then the main method is called. Then The current runtime in association with the process is obtained using getRuntime method. Then The current free memory for the current runtime is obtained using freeMemory() method.

    2. exit(int status)

    The current virtual machine is terminated using the Runtime exit(int status)method. Consider the below Java program to demonstrate the exit(int status) method of the Java Run time class.

    //a class called program is defined public class program < //main method is called public static void main(String[] args) < //the current runtime or program is caused to exit using exit(int status) method Runtime.getRuntime().exit(0); //This statement is not executed because the program is terminated by the usage of exit(int status) method above System.out.println("Checking if the program executes this statement depsite the use of exit(int status) method"); >>

    Java Runtime Class Example 2

    The output of the above program is blank.

    Explanation: In the above program, a class called program is defined. Then the main method is called. Then the current runtime or program is caused to exit using the exit(int status) method. Then the statement is not executed because the program is terminated by the usage of the exit(int status) method in the above statement.

    3. addShutdownHook(Thread Hook)

    A new hook thread is registered usingaddShutdownHook(Thread Hook)method. Consider the below Java program to demonstrate the addShutdownHook(Thread Hook)method of the Java Run time class.

    //a class called program is defined public class program < // when the program is about to exit, this class extending the thread is called static class Mess extends Thread < public void run() < System.out.println("The program is going to exit"); >> //main method is called public static void main(String[] args) < try < //the class mess is registered as shut down hook Runtime.getRuntime().addShutdownHook(new Mess()); //The thread is made to sleep for certain seconds System.out.println("Five seconds of waiting time for the program to exit"); Thread.sleep(5); >catch (Exception ex) < ex.printStackTrace(); >> >

    Java Runtime Class Example 3

    Explanation: In the above program, a class called program is defined. When the program is about to exit, this class extending the thread is called. Then the main method is called. Then the class mess is registered as shut down the hook. Then the thread is made to sleep for certain seconds.

    4. Process exec(String command) throws IOException

    The given command is executed in a separate process using Process exec(String command) throws IOExceptionmethod. Consider the below Java program to demonstrate Process exec(String command) throws IOExceptionmethod of Java Run time class

    //a class called program is defined public class program < //main method is called public static void main(String[] args) < try < // a process is created to execute google chrome Process proc = Runtime.getRuntime().exec("google-chrome"); System.out.println("Successfully started google chrome"); >catch (Exception e) < e.printStackTrace(); >> >

    Java Runtime Class Example 4

    Explanation: In the above program, a class called program is defined. Then the main method is called. Then a process is created to execute google chrome.

    5. availableProcesors()

    The number of available processors are returned using availableProcesors()method. Consider the below Java program to demonstrate the availableProcessors() method of the Java Run time class.

    //a class called program is defined public class program < //main method is called public static void main(String[] args) < //checking for the number of available processors using availableprocessors() method. System.out.println("The number of available processors are " + Runtime.getRuntime().availableProcessors()); >>

    availableProcesors() Example 5

    Explanation: In the above program, a class called program is defined. Then the main method is called. Then a check for the number of available processors is done using availableprocessors() method.

    6. freeMemory()

    The amount of free memory is returned in JVM using freeMemory()method.

    Consider the below Java program to demonstrate freeMemory() method of the Java Run time class.

    //a class called program is defined public class program < //main method is called public static void main(String[] args) < //The amount of free memory available is given by using freememory() method System.out.println("The amount of free memory available is " + Runtime.getRuntime().freeMemory()); >>

    freeMemory() Example 6

    Explanation: In the above program, a class called program is defined. Then the main method is called. Then the amount of free memory available is given by using freememory() method.

    7. totalMemory()

    The amount of total memory is returned in JVM using totalMemory()method. Consider the below Java program to demonstrate totalMemory() method of the Java Run time class.

    //a class called program is defined public class program < //main method is called public static void main(String[] args) < //The amount of total memory available is given by using totalmemory() method System.out.println("The amount of free memory available is " + Runtime.getRuntime().totalMemory()); >>

    totalMemory() Example 7

    Explanation: In the above program, a class called program is defined. Then the main method is called. Then the amount of total memory available is given by using totalmemory() method.

    This is a guide to the Java Runtime class. Here we discuss the concept of Java Runtime class through definition and their methods along with programming examples and their outputs. You can also go through our other suggested articles to learn more –

    500+ Hours of HD Videos
    15 Learning Paths
    120+ Courses
    Verifiable Certificate of Completion
    Lifetime Access

    1000+ Hours of HD Videos
    43 Learning Paths
    250+ Courses
    Verifiable Certificate of Completion
    Lifetime Access

    1500+ Hour of HD Videos
    80 Learning Paths
    360+ Courses
    Verifiable Certificate of Completion
    Lifetime Access

    3000+ Hours of HD Videos
    149 Learning Paths
    600+ Courses
    Verifiable Certificate of Completion
    Lifetime Access

    All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

    Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

    Источник

    Читайте также:  Room android studio java
Оцените статью