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去执行其他特别大的进程(也就是程序)。exec()方法有几种形式命名想要运行的程序和它的输入参数。exec()方法返回一个Process对象,可以使用这个对象控制Java程序与新运行的进程进行交互。exec()方法本质是依赖于环境。
下面的例子是使用exec()方法启动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.");
}
}
}
//此实例来自《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()方法返回对子进程的标准输入和输出。