A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 孙沛 中级黑马   /  2012-9-8 09:39  /  1639 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文



import java.io.*;
class RuntimeTest
{
public static void main(String[] args)
{
   Runtime rt=Runtime.getRuntime();
   System.out.println(rt.freeMemory());
   System.out.println(rt.totalMemory());
   try
   {
    //rt.exec("notepad");
    Process p=rt.exec("javac ArrayTest.java");
    InputStream is=p.getInputStream();
    int data;
    while((data=is.read())!=-1)
    {
     System.out.print((char)data);
    }
   
   }
   catch(Exception e)
   {
    e.printStackTrace();
   }
  
}
}

我发现应用程序不能创建自己的 Runtime 类实例,只能通过Runtime.getRuntime()获取Runtime类的实例,是不是每一个Java程序都有一个Runtime类的单一实例呢

评分

参与人数 1技术分 +1 收起 理由
唐志兵 + 1 赞一个!

查看全部评分

2 个回复

倒序浏览
本帖最后由 杨震 于 2012-9-8 10:21 编辑

是单例,你看其api

public class Runtimeextends Object
每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。可以通过 getRuntime 方法获取当前运行时。
-----------------------------------------------------------------

并且你看Runtime的源代码,是设计成单例的
部分源代码:

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}


应用程序不能创建自己的 Runtime 类实例。

评分

参与人数 1技术分 +1 收起 理由
唐志兵 + 1 赞一个!

查看全部评分

回复 使用道具 举报
private Runtime() {}

Runtime的构造方法为私有,不能被实例化,jdk文档中这样写道:每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。可以通过 getRuntime 方法获取当前运行时。

应用程序不能创建自己的 Runtime 类实例。

点评

版主,我也回答了,怎么不给我加分  发表于 2012-9-11 11:23
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马