黑马程序员技术交流社区
标题: Runtime属于单例吗? [打印本页]
作者: 孙沛 时间: 2012-9-8 09:39
标题: Runtime属于单例吗?
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类的单一实例呢
作者: 杨震 时间: 2012-9-8 10:17
本帖最后由 杨震 于 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 类实例。
作者: 唐志兵 时间: 2012-9-11 11:01
private Runtime() {}
Runtime的构造方法为私有,不能被实例化,jdk文档中这样写道:每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。可以通过 getRuntime 方法获取当前运行时。
应用程序不能创建自己的 Runtime 类实例。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |