一,Runtime类
在每个jvm进程中都会存在一个仅且一个Runtime类的对象,Runtime类的构造方法被私有化 ----单例设计模式----在Runtime类中存在一个static类型的方法用于取得Runtime类的对象----public static Runtime getRuntime() Runtime主要功能是创建新的进程操作或取得一些与运行时有关的环境属性 返回最大可用内存public native long maxMemory() long类型的一用于返回日期或者内存 public void gc()用于释放垃圾空间,gc(garbage collector)垃圾收集器,释放无用的内存空间,由系统不定期的自动回收或者手工回收 Runtime类可以调用本机的可执行程序并创建进程
package RunTime类;
public class RuntimeDemo {
public static void main ( String[ ] args) {
Runtime run = Runtime. getRuntime ( ) ;
System. out. println ( "未产生垃圾前:" ) ;
System. out. println ( "最大可用内存:" + run. maxMemory ( ) + "Byte" ) ;
System. out. println ( "所有可用内存:" + run. totalMemory ( ) + "Byte" ) ;
System. out. println ( "空余内存:" + run. freeMemory ( ) + "Byte" ) ;
String str = null;
for ( int i = 0 ; i < 2000 ; i++ ) {
str += i;
}
System. out. println ( "产生垃圾后:" ) ;
System. out. println ( "最大可用内存:" + run. maxMemory ( ) + "Byte" ) ;
System. out. println ( "所有可用内存:" + run. totalMemory ( ) + "Byte" ) ;
System. out. println ( "空余内存:" + run. freeMemory ( ) + "Byte" ) ;
run. gc ( ) ;
System. out. println ( "清理垃圾后:" ) ;
System. out. println ( "最大可用内存:" + run. maxMemory ( ) + "Byte" ) ;
System. out. println ( "所有可用内存:" + run. totalMemory ( ) + "Byte" ) ;
System. out. println ( "空余内存:" + run. freeMemory ( ) + "Byte" ) ;
}
}
package RunTime类;
public class RuntimeDemo {
public static void main ( String[ ] args) throws Exception{
Runtime run = Runtime. getRuntime ( ) ;
Process p = run. exec ( "mspaint.exe" ) ;
Thread. sleep ( 5000 ) ;
p. destroy ( ) ;
}
}
二,System类
System类的常用方法:
public static void arraycopy(Object src, int srcPos,Object dest, int destPos,int length);用于数组拷贝 public static long currentTimeMillis()取得系统当前时间 public static void gc() 这个gc()并不是System新定义的方法,而是间接调用了Runtime类的gc()方法
对象的产生一定会调用构造函数,进行一些处理操作,但是对象被回收时,却是悄无声息的,无人知晓,如果给对象一个说遗言的机会可以覆写Object类中的finalize()方法,该方法用于对象回收前的收尾工作,类似于c++的析构函数
package System类;
public class SystemDemo {
public static void main ( String[ ] args) {
long start = System. currentTimeMillis ( ) ;
String str = "" ;
for ( int i = 0 ; i < 3000 ; i++ ) {
str += i;
}
long end = System. currentTimeMillis ( ) ;
System. out. println ( "程序运行时间:" + ( end- start) + "ms" ) ;
}
}
package System类;
class birthTodie
{
public birthTodie ( )
{
System. out. println ( "----我出生了----" ) ;
}
@Override
protected void finalize ( ) throws Throwable {
System. out. println ( "----我的生命终结了----" ) ;
}
}
public class SystemDemo {
public static void main ( String[ ] args) {
birthTodie baby = new birthTodie ( ) ;
baby = null;
System. gc ( ) ;
}
}
比较final,finally,finalize:
final关键字 定义不能被继承的类,不能被覆写的方法,常量 finally关键字 异常处理的统一出口 finalize Object类提供的方法(protected void finalize() throws Throwable)指的是对象回收强前的收尾方法,即使出现了异常也不会导致程序中断执行