静态方法: public static Runtime getRuntime()
实际上可以通过Runtime 类直接运行本机的程序
package org.systemdemo;
import java.io.IOException;
public class systemdemo01 {
/**
* @param args
* @throws exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Runtime run = Runtime.getRuntime(); //单例设置
Process proc = run.exec("calc.exe"); //执行程序
Thread.sleep(2000); //看2秒
proc.destroy(); //销毁
}
}
可以让指定的程序,进行自动的关闭,exec()方法返回一个Process 类的实例,表示一个进程的对象
如果要想关闭,则使用此类中: public abstract void destroy()
Runtime 取得系统信息
package org.systemdemo;
public class runtimedeom01 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Runtime run = Runtime.getRuntime();
System.out.println(run.maxMemory()); //最大可用内存
System.out.println(run.freeMemory()); //空亲的内存空间
System.out.println(run.totalMemory()); //总共内存空间
String name ="Hello";
for (int i=0;i<1000;i++){
name +=i;
}
System.out.println(run.maxMemory());
System.out.println(run.freeMemory());
System.out.println(run.totalMemory());
}
}
垃圾回收
package org.systemdemo;
public class runtimedeom01 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Runtime run = Runtime.getRuntime();
System.out.println(run.maxMemory()); //最大可用内存
System.out.println(run.freeMemory()); //空亲的内存空间
System.out.println(run.totalMemory()); //总共内存空间
String name ="Hello";
for (int i=0;i<1000;i++){
name +=i;
}
System.out.println("--------------------");
System.out.println(run.maxMemory());
System.out.println(run.freeMemory());
System.out.println(run.totalMemory());
System.gc(); //垃圾回收
System.out.println("--------------------");
System.out.println(run.maxMemory());
System.out.println(run.freeMemory());
System.out.println(run.totalMemory());
}
}
System 类
System 类是一个系统类,例如:System.out.println()就是类中提供的操作
取得计算时间
使用此类可以取得计算的时间
public static long currentTimeMillis()
package org.systemdemo;
public class SystemDemo02 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long begin = System.currentTimeMillis();
String name ="Hello";
for (int i=0;i<50000;i++){
name +=i;
}
long end = System.currentTimeMillis();
System.out.println((end-begin)/1000);
}
}
System 与垃圾收集
在System 类中存在一个gc()方法:
public static void gc()
调用此方法实际上就是调用了Runtime类中的gc()方法
如果一个对象不用的话则就有可能进行垃圾的收集,但是如果一个对象在被收集前需要做一些收尾工作
在Object 类中存在一个方法,此方法将在对象被回收前调用:
protected void finalize() throws Throwable
package org.systemdemo;
class Person{
private String name;
public Person(String name){
this.setName(name);
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public String toString(){
return "name:"+this.name;
}
public void finalize() throws Throwable{
System.out.println("我被回收了"+this);
}
}
public class SystemDemo03 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person per = new Person("张三");
System.out.println(per);
per = null; //取消引用
System.gc(); //强制进行垃圾收集
}
}