• Tags
  •         
  • www.breakyizhan.com
  •    

    每个Java应用程序都有一个Runtime类实例,它允许应用程序与运行应用程序的环境进行交互。可以从getRuntime方法获取当前运行时。

    Java Runtime类的方法:

    1)public static Runtime getRuntime(): 此方法返回与当前Java应用程序关联的实例或Runtime对象。

    // Java program to illustrate getRuntime()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // get the current runtime assosiated with this process
            Runtime run = Runtime.getRuntime();
            // print the current free memory for this runtime
            System.out.println("" + run.freeMemory());
        }
    }
    

    输出:

    124130416
    

    2)public long freeMemory():此方法返回JVM(Java虚拟机)中的可用内存量

    // Java program to illustrate freeMemory()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // print the number of free bytes
            System.out.println("" + Runtime.getRuntime().freeMemory());
        }
    }
    

    输出:

    124130416
    

    3)public long totalMemory():此方法返回JVM(Java虚拟机)中的总内存量

    // Java program to illustrate totalMemory()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // print the number of total bytes
            System.out.println("" + Runtime.getRuntime().totalMemory());
        }
    }
    

    输出:

    124780544
    

    4)public Process exec(String command)抛出IOException:此方法在单独的进程中执行给定的命令。

    异常:

    1)SecurityException:如果存在安全管理器且其checkExec方法不允许创建子进程

    2)IOException:如果发生I / O错误

    3)NullPointerException:如果command为null

    4)IllegalArgumentException:如果命令为空

    // Java program to illustrate Process exec()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            try
            {
                // create a process and execute google-chrome
                Process process = Runtime.getRuntime().exec("google-chrome");
                System.out.println("Google Chrome successfully started");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    输出:

    Google Chrome successfully started

    注意:替换为您要启动的任何软件。在Linux上工作,google-chrome只是这样编写的。在windows / mac中可能有所不同。

    5)public void addShutdownHook(Thread hook):此方法注册一个新的虚拟机JVM Shutdown Hook线程。

    异常:

    1)IllegalArgumentException:如果已经注册了指定的挂钩,或者可以确定挂钩已在运行或已经运行

    2)IllegalStateException:如果虚拟机已经在关闭的过程中

    3)SecurityException: 如果安全管理器拒绝RuntimePermission(“shutdownHooks”)

    // Java program to illustrate addShutdownHook()
    // method of Runtime class
    public class GFG
    {
        // 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("Program exiting");
            }
        }
        public static void main(String[] args)
        {
            try
            {
                // register Message as shutdown hook
                Runtime.getRuntime().addShutdownHook(new Message());
                 
                // cause thread to sleep for 3 seconds
                System.out.println("Waiting for 5 seconds...");
                Thread.sleep(5000);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    
    

    输出:

    Waiting for 5 seconds...
    Program exiting

    6)public boolean removeShutdownHook(Thread hook):此方法取消注册先前注册的JVM Shutdown Hook虚拟机关闭挂钩。

    // Java program to illustrate removeShutdownHook()
    // method of Runtime class
    public class GFG
    {
        // 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("Program exiting");
            }
        }
        public static void main(String[] args)
        {
            try
            {
                Message p = new Message();
                // register Message as shutdown hook
                Runtime.getRuntime().addShutdownHook(p);
                 
                // cause thread to sleep for 3 seconds
                System.out.println("Waiting for 5 seconds...");
                Thread.sleep(5000);
                 
                // remove the hook
                Runtime.getRuntime().removeShutdownHook(p);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    输出:

    Waiting for 5 seconds...

    7)public int availableProcessors():此方法返回JVM(Java虚拟机)可用的处理器数。

    // Java program to illustrate availableProcessors()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // check the number of processors available
            System.out.println("" + Runtime.getRuntime()
                                        .availableProcessors());
             
        }
    }
    
    

    输出:

    4
    

    8)public void exit(int status):此方法通过启动其关闭序列来终止当前运行的Java虚拟机。

    // Java program to illustrate exit()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // cause the program to exit
            Runtime.getRuntime().exit(0);
     
            //Nothing will run now.
            System.out.println("Program Running Check");
        }
    }
    

    输出:

    No Output

    9)public void traceInstructions(boolean a):此方法启用或禁用对指令的跟踪。如果boolean参数为true,那么它将建议JVM(Java虚拟机)在执行时为虚拟机中的每条指令发出调试信息。

    // Java program to illustrate traceInstructions()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // start tracing for instructions
            Runtime.getRuntime().traceInstructions(true);
     
            System.out.println("Enabled");
            Runtime.getRuntime().traceInstructions(false);
            System.out.println("Disabled");
     
        }
    }
    

    输出:

    Enabled
    Disabled

    10)public void traceMethodCalls(boolean a):此方法启用或禁用方法调用的跟踪。如果布尔参数为truethen,则表明Java虚拟机会在调用虚拟机时为每个方法发出调试信息。

    // Java program to illustrate traceMethodCalls()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
          // start tracing for instructions
          System.out.println("Enabling..");
     
          Runtime.getRuntime().traceMethodCalls(true);
          System.out.println("Enabled");
        }
    }
    
    

    输出:

    Enabling..
    Enabled

    11)public void loadLibrary(String libname):此方法使用指定的库名称加载动态库。包含代码的文件从本地系统从常规获取库文件的位置加载。

    异常:

    1)UnsatisfiedLinkError: 如果库不存在。

    2)NullPointerException:如果libname为null。

    3)SecurityException:如果checkLink方法不允许加载指定的动态库。

    // Java program to illustrate loadLibrary()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // load a library that is home/saket/Desktop folder
            Runtime.getRuntime().loadLibrary("/home/saket/Desktop/Library");
     
            System.out.println("Library Loaded Successfully");
        }
    }
    
    

    输出:

    Library Loaded Successfully
    

    12)public void load(String filename):此方法将指定的文件名加载为动态库。filename参数必须是完整的路径名。

    异常:

    1)UnsatisfiedLinkError: 如果库不存在。

    2)NullPointerException:如果libname为null。

    3)SecurityException:如果checkLink方法不允许加载指定的动态库。

    // Java program to illustrate load()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // load a library that is home/saket/Desktop folder
            Runtime.getRuntime().loadLibrary("/home/saket/Desktop/File");
     
            System.out.println("Library Loaded Successfully");
        }
    }
    

    输出:

    Library Loaded Successfully
    

    13)public void gc():此方法运行垃圾收集器。调用此方法表明Java虚拟机花费了大量精力来回收未使用的对象,以使其当前占用的内存可用于快速重用。

    // Java program to illustrate gc()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // run the garbage collector
            Runtime.getRuntime().gc();
     
            System.out.println("Running");
        }
    }
    

    输出:

    Running
    

    14)public void runFinalization():此方法运行待完成的任何对象的终结方法。它表明HVM(Java虚拟机)花费了大量精力来运行已被发现被丢弃但其终结方法尚未运行的对象的finalize方法。

    // Java program to illustrate runFinalization()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // run the finalization
            Runtime.getRuntime().runFinalization();
     
            System.out.println("Finalized");
        }
    }
    

    输出:

    Finalized
    

    15)public long maxMemory():此方法返回Java虚拟机将尝试使用的最大内存量。如果没有固有限制,则返回值Long.MAX_VALUE。

    // Java program to illustrate maxMemory()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            // print the maximum memory
            System.out.println("" + Runtime.getRuntime().maxMemory());
        }
    }
    
    

    输出:

    922746880
    

    16)public void halt(int status):此方法强制终止当前运行的Java虚拟机。此方法永远不会正常返回。应谨慎使用此方法。

    异常:

    SecurityException:如果存在安全管理器且其checkExit方法不允许具有指定状态的退出

    // 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.");
        }
    }
    

    输出:

    no output

    17)public Process exec(String [] cmd):此方法在单独的进程中执行指定的命令和参数。这是一种方便的方法。

    异常:

    1)IndexOutOfBoundsException:如果cmd是一个空数组(长度为0)

    2)NullPointerException:如果libname为null。

    3)SecurityException:如果checkLink方法不允许加载指定的动态库。

    4)IOException:如果发生I / O错误

    // Java program to illustrate exec()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            try
            {
                String[] cmd = new String[2];
                cmd[0] = "atom";
                cmd[1] = "File.java";
                // create a process and execute cmdArray
                Process process = Runtime.getRuntime().exec(cmd);
     
                // print another message
                System.out.println("File.java opening in atom");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    
    

    输出:

    File.java opening in atom

    18)public Process exec(String command,String [] envp,File dir):此方法在具有指定环境和工作目录的单独进程中执行指定的字符串命令。这是一种方便的方法。

    异常:

    1)IndexOutOfBoundsException:如果cmd是一个空数组(长度为0)

    2)NullPointerException:如果libname为null。

    3)SecurityException:如果checkLink方法不允许加载指定的动态库。

    4)IOException:如果发生I / O错误

    // Java program to illustrate exec()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            try
            {
                // create a file with the working directory we wish
                File f = new File("/home/saket/Desktop");
                
                // create a process and execute gedit and currect environment
                Process process = Runtime.getRuntime().exec("gedit", null, f);
                System.out.println("Gedit opening.");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    输出:

    Gedit opening.

    19)public Process exec(String command,String [] envp):此方法在具有指定环境的单独进程中执行指定的字符串命令。这是一种方便的方法,其行为方式与调用exec(command,envp,null)完全相同。
    异常:

    1)IndexOutOfBoundsException:如果cmd是一个空数组(长度为0)

    2)NullPointerException:如果libname为null。

    3)SecurityException:如果checkLink方法不允许加载指定的动态库。

    4)IOException:如果发生I / O错误

    // Java program to illustrate exec()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            try
            {
                // create a file with the working directory we wish
                File f = new File("/home/saket/Desktop");
                
                // create a process and execute gedit and currect environment
                Process process = Runtime.getRuntime().exec("gedit", null);
                System.out.println("Gedit opening.");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    输出:

    Gedit opening.

    20)public Process exec(String [] cmdarray,String [] envp,File dir):此方法在具有指定环境和工作目录的单独进程中执行指定的命令和参数。给定一个字符串数组cmdarray,表示命令行的标记,以及一个字符串envp数组,表示“环境”变量设置,此方法创建一个执行指定命令的新进程。
    例外:

    1)IndexOutOfBoundsException:如果cmd是一个空数组(长度为0)

    2)NullPointerException:如果libname为null。

    3)SecurityException:如果checkLink方法不允许加载指定的动态库。

    4)IOException:如果发生I / O错误

    // Java program to illustrate exec()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            try
            {
                String[] cmd = new String[2];
                cmd[0] = "atom";
                cmd[1] = "File.java";
                // create a file with the working directory we wish
                File dir = new File("/home/saket/Desktop");
                // create a process and execute cmdArray
                Process process = Runtime.getRuntime().exec(cmd, null, dir);
                System.out.println("File.java opening.");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    输出:

    File.java opening.

    21)public Process exec(String [] cmdarray,String [] envp):此方法在具有指定环境的单独进程中执行指定的命令和参数。这是一种方便的方法。调用exec(cmdarray,envp)形式的行为与调用exec(cmdarray,envp,null)完全相同。

    例外:

    1)IndexOutOfBoundsException:如果cmd是一个空数组(长度为0)

    2)NullPointerException:如果libname为null。

    3)SecurityException:如果checkLink方法不允许加载指定的动态库。

    4)IOException:如果发生I / O错误

    // Java program to illustrate exec()
    // method of Runtime class
    public class GFG
    {
        public static void main(String[] args)
        {
            try
            {
                String[] cmd = new String[2];
                cmd[0] = "atom";
                cmd[1] = "File.java";
                // create a file with the working directory we wish
                File dir = new File("/home/saket/Desktop");
                // create a process and execute cmdArray
                Process process = Runtime.getRuntime().exec(cmd, null);
                System.out.println("File.java opening.");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    输出:

    File.java opening.

     
    转载请保留页面地址:https://www.breakyizhan.com/java/4982.html