Java教程

Java Runtime类

Java运行时类

Java运行时类用于与Java运行时环境进行交互。 Java Runtime类提供了用于执行进程,调用GC,获取总内存和可用内存等的方法。java.lang.Runtime类只有一个实例可用于一个Java应用程序。
Runtime.getRuntime()方法返回Runtime类的单例实例。

Java Runtime类的重要方法

方法 说明
public static Runtime getRuntime() 返回Runtime类的实例。
public void exit(int status) 终止当前的虚拟机。
public void addShutdownHook(Thread hook) 注册新的钩子线程。
public Process exec(String command)throws IOException 在单独的进程中执行给定命令。
public int availableProcessors() 返回编号。可用处理器的数量。
public long freeMemory() 返回JVM中的可用内存量。
public long totalMemory() 返回JVM中的总内存量。

Java运行时exec()方法

public class Runtime1{
    public static void main(String args[])throws Exception{
        Runtime.getRuntime().exec("notepad");
    //will open a new notepad }
}

如何使用Java关闭系统

您可以使用 shutdown -s 命令关闭系统。对于Windows操作系统,您需要提供关闭命令的完整路径,例如c: \\ Windows \\ System32 \\ shutdown。
在这里您可以使用-s切换到关闭系统,-r切换到重新启动系统,以及-t切换来指定时间延迟。
public class Runtime2{
    public static void main(String args[])throws Exception{
        Runtime.getRuntime().exec("shutdown -s -t 0");
    }
}

如何在Java中关闭Windows系统

public class Runtime2{
    public static void main(String args[])throws Exception{
        Runtime.getRuntime().exec("c:\\Windows\\System32\\shutdown -s -t 0");
    }
}

如何使用Java重新启动系统

public class Runtime3{
    public static void main(String args[])throws Exception{
        Runtime.getRuntime().exec("shutdown -r -t 0");
    }
}

Java运行时availableProcessors()

public class Runtime4{
    public static void main(String args[])throws Exception{
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

Java运行时freeMemory()和totalMemory()方法

在给定程序中,创建10000个实例后,可用内存将小于以前的可用内存。但是在调用gc()之后,您将获得更多的可用内存。
public class MemoryTest{
    public static void main(String args[])throws Exception{
        Runtime r=Runtime.getRuntime();
        System.out.println("Total Memory: "+r.totalMemory());
        System.out.println("Free Memory: "+r.freeMemory());
        for(int i=0;i<10000;i++){
            new MemoryTest();
        }
        System.out.println("After creating 10000 instance, Free Memory: "+r.freeMemory());
        System.gc();
        System.out.println("After gc(), Free Memory: "+r.freeMemory());
    }
}
Total Memory: 100139008
Free Memory: 99474824
After creating 10000 instance, Free Memory: 99310552
After gc(), Free Memory: 100182832
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4