一、概述
1. Runtime类封装了运行时的环境。Runntime类允许Java应用程序在他们运行时可以跟运行的环境交互。
2. 一个Java 应用程序 只有 一个 Runtime 类实例。
3. Java应用程序不能实例化Runtime对象,但可以通过 getRuntime 方法获取单例的Runtime对象。4. 一旦得到了一个当前的Runtime对象的引用,就可以调用Runtime对象的方法去控制Java虚拟机的状态和行为。
5. 当Applet和其他不被信任的代码调用任何Runtime方法时,常常会引起SecurityException异常。
二、API预览
Public Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
void |
addShutdownHook(Thread hook)
Registers a VM shutdown hook.
| ||||||||||
int |
availableProcessors()
Returns the number of processor cores available to the VM, at least 1.
| ||||||||||
Process |
exec(String[] progArray, String[] envp)
Executes the specified command and its arguments in a separate native process.
| ||||||||||
Process |
exec(String prog, String[] envp, File directory)
Executes the specified program in a separate native process.
| ||||||||||
Process |
exec(String[] progArray, String[] envp, File directory)
Executes the specified command and its arguments in a separate native process.
| ||||||||||
Process |
exec(String prog, String[] envp)
Executes the specified program in a separate native process.
| ||||||||||
Process |
exec(String prog)
Executes the specified program in a separate native process.
| ||||||||||
Process |
exec(String[] progArray)
Executes the specified command and its arguments in a separate native process.
| ||||||||||
void |
exit(int code)
Causes the VM to stop running and the program to exit.
| ||||||||||
long |
freeMemory()
Returns the number of bytes currently available on the heap without expanding the heap.
| ||||||||||
void |
gc()
Indicates to the VM that it would be a good time to run the garbage collector.
| ||||||||||
InputStream |
getLocalizedInputStream(InputStream stream)
This method was deprecated in API level 1. Use InputStreamReader instead.
| ||||||||||
OutputStream |
getLocalizedOutputStream(OutputStream stream)
This method was deprecated in API level 1. Use OutputStreamWriter instead.
| ||||||||||
static Runtime |
getRuntime()
Returns the single Runtime instance for the current application.
| ||||||||||
void |
halt(int code)
Causes the VM to stop running, and the program to exit with the given return code.
| ||||||||||
void |
load(String absolutePath)
Loads the shared library found at the given absolute path.
| ||||||||||
void |
loadLibrary(String nickname)
Loads a shared library.
| ||||||||||
long |
maxMemory()
Returns the maximum number of bytes the heap can expand to.
| ||||||||||
boolean |
removeShutdownHook(Thread hook)
Unregisters a previously registered VM shutdown hook.
| ||||||||||
void |
runFinalization()
Provides a hint to the runtime that it would be useful to attempt to perform any outstanding object finalization.
| ||||||||||
static void |
runFinalizersOnExit(boolean run)
This method was deprecated in API level 1. This method is unsafe.
| ||||||||||
long |
totalMemory()
Returns the number of bytes taken by the heap at its current size.
| ||||||||||
void |
traceInstructions(boolean enable)
Switches the output of debug information for instructions on or off.
| ||||||||||
void |
traceMethodCalls(boolean enable)
Switches the output of debug information for methods on or off.
|
三、常见的应用
1、内存管理:
Java提供了无用单元自动收集机制。通过totalMemory()和freeMemory()方法可以知道对象的堆内存有多大,还剩多少。
Java会周期性的回收垃圾对象(未使用的对象),以便释放内存空间。但是如果想先于收集器的下一次指定周期来收集废弃的对象,可以通过调用gc()方法来根据需要运行无用单元收集器。一个很好的试验方法是先调用gc()方法,然后调用freeMemory()方法来查看基本的内存使用情况,接着执行代码,然后再次调用freeMemory()方法看看分配了多少内存。下面的程序演示了这个构想。
下面的例子是使用ecec()方法启动windows的记事本notepad。这个例子必须在Windows操作系统上运行。
下面是运行的结果(当关闭记事本后,会接着运行程序,打印信息):
Java提供了无用单元自动收集机制。通过totalMemory()和freeMemory()方法可以知道对象的堆内存有多大,还剩多少。
Java会周期性的回收垃圾对象(未使用的对象),以便释放内存空间。但是如果想先于收集器的下一次指定周期来收集废弃的对象,可以通过调用gc()方法来根据需要运行无用单元收集器。一个很好的试验方法是先调用gc()方法,然后调用freeMemory()方法来查看基本的内存使用情况,接着执行代码,然后再次调用freeMemory()方法看看分配了多少内存。下面的程序演示了这个构想。
//此实例来自《java核心技术》卷一
class MemoryDemo{
public static void main(String args[]){
Runtime r = Runtime.getRuntime();
long mem1,mem2;
Integer someints[] = new Integer[1000];
System.out.println("Total memory is :" + r.totalMemory());
mem1 = r.freeMemory();
System.out.println("Initial free is : " + mem1);
r.gc();
mem1 = r.freeMemory();
System.out.println("Free memory after garbage collection : " + mem1);
//allocate integers
for(int i=0; i<1000; i++) someints[i] = new Integer(i);
mem2 = r.freeMemory();
System.out.println("Free memory after allocation : " + mem2);
System.out.println("Memory used by allocation : " +(mem1-mem2));
//discard Intergers
for(int i=0; i<1000; i++) someints[i] = null;
r.gc(); //request garbage collection
mem2 = r.freeMemory();
System.out.println("Free memory after collecting " + "discarded integers : " + mem2);
}
}
编译后运行结果如下(不同的机器不同时间运行的结果也不一定一样):
Total memory is :2031616
Initial free is : 1818488
Free memory after garbage collection : 1888808
Free memory after allocation : 1872224
Memory used by allocation : 16584
Free memory after collecting discarded integers : 1888808
Initial free is : 1818488
Free memory after garbage collection : 1888808
Free memory after allocation : 1872224
Memory used by allocation : 16584
Free memory after collecting discarded integers : 1888808
2、执行其他程序
在安全的环境中,可以在多任务操作系统中使用Java去执行其他特别大的进程(也就是程序)。ecec()方法有几种形式命名想要运行的程序和它的输入参数。ecec()方法返回一个Process对象,可以使用这个对象控制Java程序与新运行的进程进行交互。ecec()方法本质是依赖于环境。下面的例子是使用ecec()方法启动windows的记事本notepad。这个例子必须在Windows操作系统上运行。
//此实例来自《Java核心技术》卷一
class ExecDemo {
public static void main(String args[]){
Runtime r = Runtime.getRuntime();
Process p = null;
try{
p = r.exec("notepad");
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
}
}
ecec()还有其他几种形式,例子中演示的是最常用的一种。ecec()方法返回Process对象后,在新程序开始运行后就可以使用Process的方法了。可以用destory()方法杀死子进程,也可以使用waitFor()方法等待程序直到子程序结束,exitValue()方法返回子进程结束时返回的值。如果没有错误,将返回0,否则返回非0。
下面是关于ecec()方法的例子的改进版本。例子被修改为等待,直到运行的进程退出:
//此实例来自《Java核心技术》卷一
class ExecDemoFini {
public static void main(String args[]){
Runtime r = Runtime.getRuntime();
Process p = null;
try{
p = r.exec("notepad");
p.waitFor();
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
System.out.println("Notepad returned " + p.exitValue());
}
}
下面是运行的结果(当关闭记事本后,会接着运行程序,打印信息):
Notepad returned 0
请按任意键继续...
请按任意键继续...
当子进程正在运行时,可以对标准输入输出进行读写。getOutputStream()方法和getInPutStream()方法返回对子进程的标准输入和输出。