JAVA基础|常用API-Runtime

一. 说明

  • 代表程序所在的运行环境
  • Runtime是一个单例类

二. 常用的方法

方法名说明
public static Runtime getRuntime()返回与当前Java应用程序关联的运行时对象
public void exit(int status)终止当前运行的虚拟机
public int availableProcessors()返回Java虚拟机可用的处理器数
public long totalMemory()返回Java虚拟机中的内存总量
public long freeMemory()返回Java虚拟机中的可用内存
public Process exec(String command)启动某个程序,并返回代表该程序的对象

三. 使用

1. public static Runtime getRuntime()

要注意的是,Runtime是一个单例类,他的构造器被私有化了,那么如果要创建对象则需要直接调用getRuntime方法。

Runtime r = Runtime.getRuntime();

2. public void exit(int status)

这个方法大家并不陌生,在System类中也有这样的一个方法,但实际上System类中的exit方法其实调用的就是Runtime中的exit方法。

r.exit(0);

3. public int availableProcessors()

public class RuntimeTest {
    public static void main(String[] args) {
        Runtime r = Runtime.getRuntime();
        System.out.println(r.availableProcessors());
    }
}

通过它,我们可以知道java虚拟机最多能用的处理器数目

4. public long totalMemory()

返回当前java程序占用的内存数量

public class RuntimeTest {
    public static void main(String[] args) {
        Runtime r = Runtime.getRuntime();
        System.out.println(r.totalMemory() / 1024.0  + "KB");
        System.out.println(r.totalMemory() / 1024.0 / 1024.0  + "MB");
    }
}

5. public long freeMemory()

还有多少空闲的内存够java虚拟机使用?

public class RuntimeTest {
    public static void main(String[] args) {
        Runtime r = Runtime.getRuntime();
        System.out.println(r.freeMemory() / 1024.0 / 1024.0  + "MB");
    }
}

6. public Process exec(String command)

启动某个程序,并返回代表该程序的对象

public class RuntimeTest {
    public static void main(String[] args) throws IOException {
        Runtime r = Runtime.getRuntime();
        r.exec("D:\\soft\\XMind.exe");
    }
}

他就会帮我打开XMind这个程序

public class RuntimeTest {
    public static void main(String[] args) throws IOException {
        Runtime r = Runtime.getRuntime();
        r.exec("QQ");
    }
}

那如果说我们将QQ添加到了环境变量当中,就可以直接使用QQ打开了。

既然能够打开程序,那么也一定能关闭程序。

public class RuntimeTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        Runtime r = Runtime.getRuntime();
        Process p = r.exec("D:\\soft\\XMind.exe");
        Thread.sleep(5000);     //让程序在这里暂停5s后继续往下走
        p.destroy();
    }
}

首先我们知道,打开了程序后会创建这个程序的对象,这个时候我们将它赋给Process变量p,接着,为了防止一打开程序立马就关闭了,我们在打开程序与关闭程序之间通过Thread.sleep让它等待5s后再执行p.destroy方法关闭程序。

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值